# Question
Title: Unity 2d, Place object nearest to a coordinate without overlap?
I am working on a game similar to Pool (Carrom actually). I need to place coins at the center of the board or nearest possible to it without overlapping any other coins. This is a 2d game.

# Answer
Look into the Bridson algorithm for Poisson disk sampling. You can read about it here: https://www.jasondavies.com/poisson-disc/

Modify it as follows:

* When placing a new point, instead of picking any cell in the background grid from the active list, find the gridcell containing the closest possible point. Use the following formula: `Δx = Cx - Gx - max(s, Cx - Gx)` `Δy = Cy - Gy - max(s, Cy - Gy)` `minDistSquared=Δx²+Δy²`. `Cx, Cy` is the centerpoint, `Gx, Gz` is the starting point of the grid cell, and `s` is the side of the square. It would probably help to sort your active list by this metric, or use a sorted list structure.
* Instead of picking points randomly and rejecting after `k` tries, try all intersection points between the `2r`-radius circles around each point which cover it. Also try the closest point on/inside the square `<Gx + max(s, Cx - Gx), Gy + max(s, Cy - Gy)>`, and the closest point on each circle to the center, if that point is inside the square. Pick the closest valid point. Points are invalid when they're too far inside the range of existing circles. In the special case that the circle is exactly on the center, and there are no intersections between it and other circles, choose a random point on it.
    + If you found a valid point, search the list for all squares whose *maximum* distance can possibly be closer than it. Use this formula: `Δx = max(|Cx - Gx|, |Cx - Gx - s|)` `Δy = max(|Cy - Gy|, |Cy - Gy - y|)` `maxDistSquared=Δx²+Δy²`. Try all those squares to see if you can find a closer valid point.
    + If you didn't find a valid point (not even in the current/original square), keep checking further out in the active list until you find one. Perform the above bullet point once you have.
* After your coins have moved around a result of your game mechanics, fully refresh the state of the underlying background / search grid and active list to account for the new point locations. When placing new coins, continue the algorithm from this updated state.

If you want your implementation to be simpler, and your board is small enough, you can probably omit the active list and just check every grid cell -- just keep track of the furthest point that was placed using the modified poisson rules (resets to the centerpoint when the search is refreshed). You will probably still want to store the order of cells to check in a list though.

And if you only ever need to place one coin after the state is refreshed, then you don't need to update the state of the grid/list or keep track of the furthest Poisson-placed point, just count on refreshing the whole thing each time.
> 2 votes

---
Tags: unity
---


# Question
Title: How can I limit the y-rotation of a cinemachine POV camera based on the player's direction?
I'm using Unity (2019.4.11.f1, HDRP).
My goal is to create a first-person POV camera.

To this purpose, I tied a Cinemachine (2.7.3) Virtual Camera to the head of a third person player character (one from the Basic Locomotion demo of this asset).
The *Body* of the camera is set to 'Hard Lock to Target', *Aim* to 'POV', and *Recenter Target* to 'Follow Target Forward'. This works fine.

The camera has a Horizontal Axis Value Range (-# to #), that limits the rotation of the camera, but I cannot figure out how to tie this to the rotation of the *Follow* component (the head of the avatar).
When I walk my character around, the camera can only rotate within the set Value Range angle that has it's 0-point in one absolute direction (let's say north), independent of the player's orientation.
It seems to use World Orientation, but I don't know and wasn't able to find out where to change that.

Does anyone know how I can change this behaviour?

# Answer
I was figuring out a first person controller and had a similar problem. This is what worked for me, I think it should help but I may be misunderstanding, or there may be a better way.

First, you didn't specify where the vcam is in the hierarchy. I'm assuming its at the root level, which would explain why it's using world space orientation. If it was a child of the character's head, it should behave according to that local space.

`Body` should probably be set to "do nothing" if you don't want the vcam to control its own movement. I think "hard lock to target" emulates the effect of having the camera attached to the target, but doesn't actually put the camera into the target's local coordinate system. Again, that seems likely to be the cause of your problem.

Second, the POV component allows the player to control the camera, but what you actually want the player to be doing is controlling the *character*. In other words, you don't want the camera to be able to move farther than the character can turn, or to mis-match between where the head and camera are. You can certainly make it work but you'll have a complicated setup that'll be difficult to tweak, just to achieve a simple effect.

So the easiest solution is to set up your character controller (I used the Unity Standard Assets one and modified that) and just attach a virtual camera set to "do nothing" where the camera would normally be. Then you can still use all the cinemachine features to switch cameras and whatnot as normal.
> 1 votes

---
Tags: unity, camera, cinemachine
---


title: GUI.BeginScrollView not working

text:
# Question
Title: GUI.BeginScrollView not working
I made a GUI Tool for Unity I tryed to add ScrollView like this before the for loop that creates GameObject buttons :

```
scrollPosition = GUI.BeginScrollView(new Rect(Screen.width-1,20,0,Screen.height-60),scrollPosition,new Rect(0,0,Screen.width-20, Screen.height-80),false,false,GUIStyle.none,GUI.skin.verticalScrollbar);

```

and I use GUI.EndScrollView after the for loop that creates Buttons

# Answer
I misread the definition of ScrollView. The first Rect defines the Rectangle on the screen to use for the ScrollView. and the Second is the rectangle used inside the scrollview. that means that i should not position ScreenWidth-1 which makes it hidden from me

In other words, i should replace `Screen.width-1` with `0`
> 1 votes

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


# Question
Title: Quaternion rotation around center, undefined behavior
Here's my code:

```
vec4 qx, qy, qz;
mat4 mx, my, mz;

// rotating using quaternions
glm_quat(qx, to_radians(a->rx), 1.0f, 0.0f, 0.0f);
glm_quat(qy, to_radians(a->ry), 0.0f, 1.0f, 0.0f);
glm_quat(qz, to_radians(a->rz), 0.0f, 0.0f, 1.0f);

// turning the quaternions into matrices
glm_quat_mat4(qx, mx);
glm_quat_mat4(qy, my);
glm_quat_mat4(qz, mz);

mat4 trans = {
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1
};

mat4 rot = {
    1, 0, 0, 0,
    0, 1, 0, 0,
    0, 0, 1, 0,
    0, 0, 0, 1
};

mat4 final;

// combining the rotations into one.
glm_mat4_mulN((mat4* []){&mx, &my, &mz}, 3, rot);

// translating the `trans` matrix.
glm_translate(trans, (vec3){ a->x, a->y, a->z });

// finally combining the translation with the rotation into one.
glm_mat4_mul(trans, rot, final);

```

My desired behavior is that the object rotates around its center, but here is what happens instead:

So , it seems that my object is rotating around some weird other undefined point. I have no idea why this happens.

Any ideas? Thank you.

# Answer
> 1 votes
## For similar questions;

**cglm** povides a few *pe-defined* rotation APIs (new more APIs may be added in the future if needed):

* rotate vector using axis/angle

`glm_vec3_rotate(vec3 v, float angle, vec3 axis)`
* apply rotation matrix to vectoo

`glm_vec3_rotate_[m4 | m3](mat4 m, vec3 v, vec3 dest)`
* rotate vector using quaternion

`glm_quat_rotatev(versor q, vec3 v, vec3 dest)`
* rotate existing transform matrix using quaternion

`glm_quat_rotate(mat4 m, versor q, mat4 dest)`
* rotate existing transform matrix using quaternion at pivot point

`glm_quat_rotate_at(mat4 m, versor q, vec3 pivot)`
* rotate NEW transform matrix using quaternion at pivot point

`glm_quat_rotate_atm(mat4 m, versor q, vec3 pivot)`
* rotate existing transform matrix around given axis by angle

`glm_rotate(mat4 m, float angle, vec3 axis)`
* rotate existing transform around given axis by angle at given pivot point (rotation center)

`glm_rotate_at(mat4 m, vec3 pivot, float angle, vec3 axis)`
* creates NEW rotation matrix by angle and axis at given point

`glm_rotate_atm(mat4 m, vec3 pivot, float angle, vec3 axis)`
* rotate existing transform matrix around X axis by angle and store result in dest

`glm_rotate_[x|y|z](mat4 m, float angle, mat4 dest)`
* 2D: creates NEW rotation matrix by angle around Z axis

`glm_rotate2d_make(mat3 m, float angle)`
* 2D: rotate existing 2d transform matrix around Z axis by angle and store result in same matrix

`glm_rotate2d(mat3 m, float angle)`
* 2D: rotate existing 2d transform matrix around Z axis by angle and store result in dest

`glm_rotate2d_to(mat3 m, float angle, mat3 dest)`
* Euler Angles APIs (this will be updated)

```
CGLM_INLINE void glm_euler_angles(mat4 m, vec3 dest);
CGLM_INLINE void glm_euler(vec3 angles, mat4 dest);
CGLM_INLINE void glm_euler_xyz(vec3 angles, mat4 dest);
CGLM_INLINE void glm_euler_zyx(vec3 angles, mat4 dest);
CGLM_INLINE void glm_euler_zxy(vec3 angles, mat4 dest);
CGLM_INLINE void glm_euler_xzy(vec3 angles, mat4 dest);
CGLM_INLINE void glm_euler_yzx(vec3 angles, mat4 dest);
CGLM_INLINE void glm_euler_yxz(vec3 angles, mat4 dest);
CGLM_INLINE void glm_euler_by_order(vec3         angles,
                                     glm_euler_seq ord,
                                     mat4         dest);

```
* using matrix, quaternion... to rotate manually... or `_look[_at]()` for view matrix maybe...
* ...

Knowing existing APIs may help a lot. `_rotate_at()` and `rotate_atm()` functions will help to rotate around a point. Othewise you need to the math manually (translate to origin then rotate then tanslate back...) the existing APIs are optimized and may be more optimized by time...

Also converting and combining matrices are redundant, instead multiplying quaternions will do the job and then the quat can be converted to rotation matrix.

cglm Github and cglm Documentation

# Answer
> 0 votes
Affine transformations use the following order:

1. Translate
2. Rotate
3. Scale

I'm not sure what version of glm you are using, but the code looks very strange.

In C++ terms, it should look something like this:

```
// rotating using quaternions
glm::vec3 x(1.0f,.0f,.0f);
glm::vec3 y(.0f,1.0f,.0f);
glm::vec3 z(.0f,.0f,1.0f);

glm::quat q(1.0f);
q = glm::quat::rotate(q, x, to_radians(a->rx));
q = glm::quat::rotate(q, y, to_radians(a->ry));
q = glm::quat::rotate(q, z, to_radians(a->rz));

glm::mat4 ident(1.0f), final(1.0f);

glm::mat4 translate = glm::translate(ident, a->position);
glm::mat4 rotate = glm::toMat4(q); // Or something like that
glm::mat4 scale = glm::scale(glm::mat4(1.0f), a->scale);

final = scale * rotate * translate * ident; // In code order is right to left.

```

The above code is using the current glm API, so I can only assume you are either using a very old version, or are intentionally abstracting the actual glm calls. In any case:

1. Order matters. To rotate around a point, rotate first, then translate. To rotate around the centre of the object translate first, then rotate: A*B != B*A. Read https://en.wikipedia.org/wiki/Affine\_transformation for more information.
2. Resource Acquisition Is Initialization(RAII): ALWAYS initialize your matrices to the identity matrix values: GLM matrices are internally an array of floats, so when assigned, will just use whatever data happens to be in that memory at the time. If you're lucky, it will be zeroed. Don't count on that. In fact, follow RAII best practices and always initialize all your variables. It might seem tedious, but I guarantee you, as your code gets more complex, uninitialized numerical data will account for more than half your weird, hard to explain behavior. Read https://en.wikipedia.org/wiki/Resource\_acquisition\_is\_initialization for more information.

---
Tags: opengl, rotation, quaternion, c
---


# Question
Title: How to make an object jump an equal height whenever it hits the ground?
So, I want to make an object jump an equal height whenever it touches the ground. Something like a bouncing ball. But I can't use Physics Materials. Here are some ways that I tried:

Used Physics.CheckSphere:

```
isGrounded = Physics.CheckSphere(rayPoint.position, grounDistance, groundLayer);

if(isGrounded )
{
    rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}

```

Used Raycast:

```
bool groundHit = Physics.Raycast(rayPoint.position, -transform.up, rayDistance, groundLayer);

if(groundHit)
{
    rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}

```

In each cases, the object jumps a different amount of height each time it reaches the ground. How can I make it jump an equal height each time?

# Answer
Are you getting different results per jump on the same item, or are you trying to replicate the same height on different objects?

ForceMode.Impulse is dependent on the mass of the object you're using it on (https://docs.unity3d.com/ScriptReference/ForceMode.Impulse.html). If you want it to ignore the mass, ForceMode.VelocityChange (https://docs.unity3d.com/ScriptReference/ForceMode.VelocityChange.html) should do the trick.

Example:

```
if(groundHit)
{
    rb.AddForce(transform.up * jumpForce, ForceMode.VelocityChange);
}

```

---

Edit:

Something I didn't consider before this, how collisions are detected does appear to make a difference. If your Rigidbody is still falling when you trigger the "AddForce()" function, you'll be adding upward velocity with opposing downward force.

I used this example for detecting when my GameObject collided with the ground.

Slightly shortened, and changed "collision.contacts\[0\]" to "collision.GetContact(0)", the editor warns that the first one causes memory garbage. Using this, I got the same height every jump.

```
void OnCollisionEnter(Collision col)
{
    if(Vector3.Dot(col.GetContact(0).normal,Vector3.up) > 0.5)
    {
        isJumping = false;
    }
 }

```

Per Evolor's comment, (which they should definitely turn into an answer so I can upvote it), you can set velocity directly instead of adding force.

---

Adding this to my answer since you asked about changing the local velocity of the rigidbody as well. The discussion there seems to explain doing that pretty well.
> 3 votes

# Answer
Use Pos = S\*T +(1/2)Gt^2 this formula

```
public class ABCD : MonoBehaviour
{
    float spd = 10;
    float t = 0;
    float g = -9.8f;

    private void Update()
    {
        t += Time.deltaTime;
        float y = spd * t + (1f / 2f) * g * (t * t);
        transform.position = new Vector3(0, y, 0);

        if(y < 0)
        {
            t = 0;
        }
    }
}

```
> -1 votes

---
Tags: unity, jumping
---


title: How to Convert Sprite into Texture

text:
# Question
Title: How to Convert Sprite into Texture
I Have image with a sprite and i want to change this image sprite to Texture so that I can assign it to the material And i don't want to keep multiple copies for each image as a sprite and texture.

Is there any way to change sprite to texture at run time?

# Answer
> 3 votes
```
// assume "sprite" is your Sprite object
 var croppedTexture = new Texture2D( (int)sprite.rect.width, (int)sprite.rect.height );
 var pixels = sprite.texture.GetPixels(  (int)sprite.textureRect.x,
                                         (int)sprite.textureRect.y,
                                         (int)sprite.textureRect.width,
                                         (int)sprite.textureRect.height );
 croppedTexture.SetPixels( pixels );
 croppedTexture.Apply();

```

this should work for you. you can follow this thread for more info: https://answers.unity.com/questions/651984/convert-sprite-image-to-texture.html

# Answer
> 2 votes
For just converting Image's sprite To Texture use this:

> Image.sprite.texture

And this will do the Job.

Thanks @virtouso for sharing the thread.

# Answer
> 0 votes

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

#if UNITY_EDITOR
using UnityEditor;
#endif

public class SpriteToPNGFile : MonoBehaviour
{
    [SerializeField] private Sprite _sprite;
    public Sprite _Sprite => this._sprite;

    [SerializeField] private Texture2D _texturePreview;
    public Texture2D _Name => this._texturePreview;

    public void SaveTexture(Texture2D texture2D)
    {
        this._texturePreview = texture2D;

        byte[] bytes = texture2D.EncodeToPNG();

        string directoryPath = Application.dataPath + "/SpriteToPNGFileOutput";

        if (!Directory.Exists(directoryPath))
        {
            Directory.CreateDirectory(directoryPath);
        }

        File.WriteAllBytes(directoryPath + "/Tex_" + GUID.Generate() + ".png", bytes);

        Debug.Log(bytes.Length / 1024 + "Kb was saved as: " + directoryPath);

#if UNITY_EDITOR
        AssetDatabase.Refresh();
#endif
    }

    public void SaveSpriteAsTexture(Sprite sprite)
    {
        Texture2D texture = new Texture2D(
            (int)sprite.textureRect.width,
            (int)sprite.textureRect.height
        );

        Color[] pixels = sprite.texture.GetPixels(
            (int)sprite.textureRect.x,
            (int)sprite.textureRect.y,
            (int)sprite.textureRect.width,
            (int)sprite.textureRect.height
        );

        texture.SetPixels(pixels);
        texture.Apply();

        this.SaveTexture(texture2D: texture);
    }

#if UNITY_EDITOR
    [CustomEditor(inspectedType: typeof(SpriteToPNGFile))]
    public class SpriteToPNGFileEditor : Editor
    {
        private SpriteToPNGFile _target;

        private void OnEnable()
        {
            this._target = (SpriteToPNGFile)this.target;
        }

        public override void OnInspectorGUI()
        {
            base.OnInspectorGUI();

            if (GUILayout.Button("Generate PNG"))
            {
                this._target.SaveSpriteAsTexture(sprite: this._target._sprite);
            }
        }
    }
#endif
}
```

---
Tags: unity, textures, sprites, materials
---


title: UE4 doesnt work with subfolders

text:
# Question
Title: UE4 doesnt work with subfolders
I am trying to create a file structure for my code in c++classes/Myproject (in UE4 editor). I added a new class and in UE4s "Add C++ Class" dialog box I set the path for the created scripts as MyProject/Source/MyProject/test, test being the subfolder I am trying to create, however when the editor finishes generating the files I get an error saying that it failed to find the files it generated.

> ...\MyProject\test\SysGen.cpp(4): fatal error C1083: Cannot open include file: 'test/SysGen.h': No such file or directory

In visual studio I can see and open the generated scripts, but it fails to compile. What do I need to do for this to work?

here are the files image taken from visual studio:

# Answer
> 1 votes
From your picture, it seems that the cpp file is trying to look inside a subfolder called test for the header file where there isn't one.

In your #include, remove the test/ and it should clear this up.

---
Tags: unreal-4
---


# Question
Title: How can I directly write pixel data in an SDL window using surfaces?
I'd like to directly modify pixels in my window in SDL 2. I expect this code to display an entirely red window, but instead I'm getting an all black window.

I'm able to get it working if I directly write to `window_surface` with the same technique, but not by blitting another surface. I'd like to get it working this way at least just for the purposes of understanding.

```
#include <SDL.h>

int main()
{
    SDL_Init(SDL_INIT_EVERYTHING);

    SDL_Window *window = SDL_CreateWindow("Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1600, 900, 0);

    SDL_Surface *window_surface = SDL_GetWindowSurface(window);

    SDL_Surface *canvas = SDL_CreateRGBSurfaceWithFormat(
        0, 1600, 900, 32, SDL_PIXELFORMAT_RGBA8888
    );

    Uint32 *buffer = (Uint32*) canvas->pixels;
    int row    = 0;
    int column = 0;
    int offset;
    Uint32 color;
    SDL_UnlockSurface(canvas);
    while (row < 900)
    {
        column = 0;
        while (column < 1600)
        {
            offset = row * 1600 + column;
            color = SDL_MapRGBA(canvas->format, 255, 0, 0, 255);
            buffer[offset] = color;
            column++;
        }
        row++;
    }
    SDL_LockSurface(canvas);

    int quit = 0;
    SDL_Event event;
    while (!quit)
    {
        while (SDL_PollEvent(&event))
        {
            if (event.type == SDL_QUIT)
            {
                quit = 1;
            }
        }

        SDL_BlitSurface(canvas, 0, window_surface, 0);
        SDL_UpdateWindowSurface(window);

        SDL_Delay(10);
    }

    SDL_Quit();

    return 0;
}

```

# Answer
> 0 votes
It's the other way around, first you call SDL\_LockSurface(canvas); then SDL\_UnlockSurface(canvas); Just swap those two lines and it works.

---
Tags: sdl, sdl2
---


# Question
Title: Optimal Way to Create Card Templates in Unity 2D
I have a couple questions involving software architecture and best practices in Unity. Although I have some programming knowledge, I am just starting with Unity and C#, and I would like some input from people with more experience than myself so I can learn Unity the right way and do not let bad habits take root.

In a nutshell: I am trying to put together a simple card drawing mechanic, where I would define a card layout (kind of like a class) and then initialise two-three at a time with data pulled randomly from a data source. Cards would have standard attributes like, cost, image, name, etc.

My first question is: what would be the optimal way to define the card template? Off the top of my head, I would say that it should be a prefab. But I am aware that there are other options as well, such as scriptable objects.

My other, related question, is: what would be a good way to store card data with future expandability in my mind. If my idea ever comes to fruition, I would like to release new card packs periodically, expanding the main card stock bit-by-bit. So, I am guessing, storing it in a simple JSON is probably not the best choice from a software architecture point of view.

Thank you for your answers!

# Answer
Your guesses about how to plan your game look good and give you room for further improvement too. Prefabs make GameObject management easier, and let you edit once and apply changes everywhere in your project. The JSON format is easy to understand and debug, and enough for your starting builds; it isn't either good or bad, it just depends on what you need to do.

This means all answers here are going to be subjective and depend on others' thinking and approach to coding, then you may want to be more specific about what you need to solve.

**My two pennies worth:**

Scriptable objects are a good way to set up instances sharing the same codebase but behaving differently. You can easily change public variables through the inspector, then creating the same prefab with different starting values. This approach can be combined with prefab variants so that Unity recognises these as the same GameObject type (even if you have 10 different variants).

Card info can be stored as JSON, plain text, a dictionary... Any solution is suitable as long as it works - until you want to optimise and improve your workflow. You'd want to store unique information only, such as cards name, cost, description; whereas features like spawn, mulligan, and special effects are scripted and can be *referenced* with simple labels (different cards may have the same effect, even with different parameters), adding/removing them at runtime.

---

**EDIT: game state and animations**

Additionally, I suppose your game needs animations (e.g. drawing cards, giving visual feedback on attacks/effects...) that you need to separate from the game logic:

* The internal game state should only step forward based on individual players' actions and in-game chained effects;
* Animations should purely and simply animate stuff.

This means that the animation component should *never* tell the game logic to step forward so that it can display the next animation. It's the other way round: the game logic tells the animation component that *something happened* and that a certain animation must be played; once the animation has finished, the logic can move forward and update the game state once again, triggering a new animation, and so on.

How to do that? Unity features Coroutines, which you can treat like functions that give you control over their execution time rather than returning right after completion. Therefore, you can tell a coroutine to do something and wait for a certain amount of seconds before moving on. And, you can also nest coroutines:

* `Coroutine1` starts;
* `Coroutine1` calls `Coroutine2` and pauses execution;
    + `Coroutine2` starts;
    + `Coroutine2` does something;
    + `Coroutine2` returns;
* `Coroutine1` resumes execution.

You can now replace `Coroutine1` with your game logic and `Coroutine2` with any routine animating cards and effects in your current game. All animations will end before moving on with the game, BUT it's the game logic that waits for animation completion and not the animation itself to step the game state forward.
> 2 votes

---
Tags: unity, prefabs, scriptable-object
---


# Question
Title: How to properly overflow 2D coordinates on an overflowing/circular map?
I made a simple Snake game designed for trying Snake bots. I thought the base map functions work, but now I found there is an error. What I need is to properly translate any coordinates outside the actual map to coordinates within it.

For example, if you're at the right edge of a 10x10 map and you go to (zero-indexed) \[10, 5\], you'd expect to pop out at \[0, 5\]. That works in my implementation, but not the negative overflow. I tried a lot of formulas in the dev console and just can't figure it out. Consider this code:

```
    /**
     * Normalizes overflow of a point so that it is within the map
     * @param {number|Vector2} x
     * @param {number} y
     * @returns {Vector2}
     */
    normalizePoint(x, y) {
        if (x instanceof Vector2) {
            y = x.y;
            x = x.x;
        }

        // auto overflow
        if (x >= this.size) {
            x = (x % this.size);
        }
        else if (x < 0) {
            // ???
        }
        if (y >= this.size) {
            y = (y % this.size);
        }
        else if (y < 0) {
            // one of the formulae I tried, does not work for all values
            y = this.size + (y-1) % this.size;
        }
        return new Vector2(x, y);
    }

```

`Vector2` is a simple object with properties `x` and `y`. `this.size` represents the map size. For negative coordinates, I am not getting the correct results. I want overflowing X and Y coords to resolve to the same numbers. For example for a 5x5 map, all rows should be equal X coords after normalizing:

| Real map coord X: | 0 | 1 | 2 | 3 | 4 |
| --- | --- | --- | --- | --- | --- |
| Negative alternatives: | -5 | -4 | -3 | -2 | -1 |
| Negative alternatives: | -10 | -9 | -8 | -7 | -6 |

I would prefer it to be a O(1) formula, rather than some weird loop. With a loop, I solved it like this:

if (x < 0) {
            while (x < 0) {
                x += this.size;
            }
        }

```
</code></pre>

# Answer
If you need to wrap just a few steps out of bounds (up to negative `size`), then you can do this like so:

```
(size + coordinate) % size

```

When `coordinate = -1` then this gives you `(size - 1) % size = size - 1`.

And when `coordinate = size` then this gives you `(size + size) % size = 0`.

For any value in between (`0` to `size - 1`), this behaves the same as the identity function, giving you `coordinate` back unchanged.

So you can safely use this one formula for all cases, with no `if` branching required to change behaviour depending on whether you're overflowing, underflowing, or in-range.

---

If you need to wrap further than negative size, you can increase the multiple of `size` you add inside the parentheses:

```
(3 * size + coordinate) % size

```

This will wrap correctly from `-3 * size` up to the maximum representable integer, and you can keep growing that coefficient if you need.

---

If you have no bound on how far your coordinates can go in the negative direction, then you can do it with a double modulo:

```
((coordinate % size) + size) % size

```

The inner modulo brings us into the range of `-(size-1)` to `(size -1)` and then we apply the original formula around it to bring us to `0` to `size - 1`.

---

Just to note, this is not circular wrapping, but toroidal. Your map area remains a rectangle, not a circle.
> 3 votes

---
Tags: 2d, mathematics, javascript, algorithm
---


# Question
Title: How to run a timer parallel to a series of coroutines and WaitForSeconds
In the code below, I have a cycle for enemies appearing and disappearing.

```
IEnumerator EnemyCycle()    {
while (isRepeating)
{

for (int j = 0; j < enemies.Length; j++) {

    canStartUpdatingReset = true;
    Enemy currentEnemy = enemies [j];
    var _myMaterial = currentEnemy.GetComponent<Renderer>().material;
    var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 0f, fTime, currentEnemy.gameObject, false));

coroutinesToStop.Add(_currentFade);

if (currentEnemy.hasWeapon) {
                weaponCycleCoroutines.Add(StartCoroutine(FadeToForWeapon(currentEnemy.weapon.GetComponent<Renderer>().material, 0f, fadeTime, currentEnemy.weapon, false)));

            }
}

yield return new WaitForSeconds (hideTime);

for (int j = 0; j < enemies.Length; j++) {

    Enemy currentEnemy = enemies [j];
    var _myMaterial = currentEnemy.GetComponent<Renderer>().material;
    var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 1f, fTime, currentEnemy.gameObject, true));

     coroutinesToStop.Add(_currentFade);
if (currentEnemy.hasWeapon) {
weaponCycleCoroutines.Add(StartCoroutine(FadeToForWeapon(currentEnemy.weapon.GetComponent<Renderer>().material, 1f, fadeTime, currentEnemy.weapon, true)));
}
yield return new WaitForSeconds (showTime);

        }
    }
}

```

I have an `enemyCycleDuration` `float` which is

```
enemyCycleDuration = 60*(hideTime + fadeTime + showTime + fadeTime)

```

Note that `fadeTime` comes from `FadeToForWeapon` and `FadeToForEnemy`. The idea here is I want the `enemyCycleDuration` to be run in parallel to `EnemyCycle()` so it is reset (please see code below) at the same time that

```
yield return new WaitForSeconds (showTime);

```

is reached in the `EnemyCycle()`.

I am resetting `enemyCycleDuration` in the following way in the `update` method but `EnemyCycle()` seems to be ahead of `enemyCycleDuration`, always completing before `enemyCycleDuration` is reset. How can I get both to run parallel to each other in timing and complete at the same time?

```
if (canStartUpdatingReset)  {
timeElapsed +=1;
if(timeElapsed >= enemyCycleDuration) {

    timeElapsed = 0;

    Debug.Log ("Reset CycleDuration");
    }
}

```

# Answer
> 1 votes
What is the variable "hideTime"? I don't see where the value of it is being determined.

If I'm understanding your code correctly; coroutines are started/stopped in "EnemyCycle()" here:

```
while (isRepeating)
{

for (int j = 0; j < enemies.Length; j++) {

    canStartUpdatingReset = true;
    Enemy currentEnemy = enemies [j];
    var _myMaterial = currentEnemy.GetComponent<Renderer>().material;
    var _currentFade = StartCoroutine(FadeToForEnemy(_myMaterial, 0f, fTime, currentEnemy.gameObject, false));

coroutinesToStop.Add(_currentFade);

if (currentEnemy.hasWeapon) {
                weaponCycleCoroutines.Add(StartCoroutine(FadeToForWeapon(currentEnemy.weapon.GetComponent<Renderer>().material, 0f, fadeTime, currentEnemy.weapon, false)));

            }
}

```

What determines the value of this "isRepeating" loop? It looks like the routines started and stopped while nothing is delaying the loop. That leaves the two timers

```
yield return new WaitForSeconds (hideTime);

```

and

```
 yield return new WaitForSeconds (showTime);

```

These two, combined being the total time the cycle will run. Then you have the cycle duration variable which is 60 * those two timers and the additional values:

```
enemyCycleDuration = 60*(hideTime + fadeTime + showTime + fadeTime)

```

It's very possible I'm misunderstanding your code, which if I am, please let me know where I went wrong. But it looks like the time for the other cycle, EnemyCycleDuration will always be drastically higher then the EnemyCycle() routine.

You might try the "WaitWhile" yield statement in place of "WaitForSeconds", then you can simply tell it to wait until "EnemyCycleDuration" meets the the desired value like this:

```
yield return new WaitWhile (() => EnemyCycleDuration >= [some duration here]);

```

If you want it the other way around, you can change how EnemyCycleDuration is calculated that way your "CanStartUpdating" loop completes sooner.

---
Tags: unity
---


title: Lag Spike When Creating Model

text:
# Question
Title: Lag Spike When Creating Model
I am creating a game using OpenGl in c++. Whenever I create a new model while the game is running, such as fire a bullet, there is a huge lag spike. The function that creates the model is below.

```
    std::string jsonString;
    jsonString = file->load(type);
    json jf = json::parse(jsonString); //Might be causing the lag

    indicesSizeTexture = jf["textureIndices"].size();
    verticesSizeTexture = jf["textureVertices"].size();
    indicesSizeCollision = jf["collisionIndices"].size();
    verticesSizeCollision = jf["collisionVertices"].size();
    verticesTexture = new float[verticesSizeTexture * 8];
    verticesCollision = new float[verticesSizeCollision * 8];
    verticesCollisionUpdated = new float[verticesSizeCollision * 8];

    indicesTexture = new int[indicesSizeTexture];
    indicesCollision = new int[indicesSizeCollision];

    for (int i = 0; i < verticesSizeTexture; i++) {  //responsible for just the texture vertices
        verticesTexture[i] = jf["textureVertices"][i];
    }
    for (int i = 0; i < indicesSizeTexture; i++) { // responsible for just the texture indices
        indicesTexture[i] = jf["textureIndices"][i];
    }
    for (int i = 0; i < verticesSizeCollision; i++) {  //responsible for just the collision vertices
        verticesCollision[i] = jf["collisionVertices"][i];
        verticesCollisionUpdated[i] = verticesCollision[i];
    }
    for (int i = 0; i < indicesSizeCollision; i++) { // responsible for just the collision indices
        indicesCollision[i] = jf["collisionIndices"][i];
    }

    //binds id
    glGenBuffers(1, &VBO);
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &EBO);
    glGenTextures(1, &texture);

    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, verticesSizeTexture * 8 * sizeof(float), verticesTexture, GL_STATIC_DRAW);
    // position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);
    //texture
    glBindTexture(GL_TEXTURE_2D, texture);
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
    glEnableVertexAttribArray(2);

    stbi_set_flip_vertically_on_load(true);
    unsigned char* data = stbi_load(texturePathString.c_str(), &width, &height, &nrChannels, 0);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
    glGenerateMipmap(GL_TEXTURE_2D);
    stbi_image_free(data);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

```

I stripped out a lot of parts that I am almost certain aren't causing the lag. There is a lot of stuff going on, but it is mostly simple mathematical operations. The only parts that I think could be causing the lag is the json section used for loading the model data. The model data is stored in a variable from `file` as a string. I need the json section for the data storage though. What could be causing the lag? should I find a different data storage type? What if I created a bullet offscreen on startup, then copied it whenever I needed it? The specific json library I am using is https://github.com/nlohmann/json

# Answer
> 1 votes
**This is normal expected behaviour when you create resources at runtime**.

In your case, you are:

* Loading a file from disk.
* Parsing that file (and parsing plain text is a **slow** runtime operation).
* Allocating a bunch of memory and copying data into it.
* Creating a bunch of GL objects.
* Transferring data to those objects.
* Tearing down all the temp stuff that was set up to do all of this work.

**You shouldn't be surprised that you get lag spikes**.

To resolve, you can try:

* Use a binary file format instead (*parsing plain text is an exercise that only appeals to the type of person who likes writing plain text parsers*). You can efficiently load models without needing to parse them this way, by e.g. memory-mapping a file and passing the resulting pointer directly to glBufferData. It should reduce or remove the overhead from parsing text and copying data around, but will not help with overhead from hitting the disk or from creating GL objects at runtime.
* Don't create resources at runtime; create them during program startup instead.
* Try spinning off an extra thread to do the loading - although if you need to use the object in the same frame as you load it, this may be of minimal benefit, and in any case will introduce possibly unwanted complexities to your code.
* If you really must load at runtime from plain text files, then just accept that you're going to get this behaviour.

---
Tags: opengl, optimization, lag
---


# Question
Title: How to transfrom CollisionPolygon2D according to the Vertex Shader applied to a Sprite?
Consider this:

```
* KinematicBody2D
- * Sprite
- * CollisionPolygon2D

```

And a vertex shader:

```
shader_type canvas_item;

void vertex() {
    VERTEX.y += sin(2.0 * TIME) * 10.0;
}

```

When the vertex shader is added to the `CanvasItem.material` of the Sprite and the CollisionPolygon2D they both move at the same time:

But if one modifies the shader like that:

```
void vertex() {
  VERTEX.y += sin(UV.y * 2.0 * TIME) * 10.0;
}

```

It produces that:

How to transfrom CollisionPolygon2D according to the Vertex Shader applied to the Sprite?

# Answer
You probably don't want to do this, for reasons I'll mention below. However, to answer the question…

The reason why you don't see the `CollisionPolygon2D` move the same way is because it does not have `UV` coordinates set (because it does not need to be textured).

We write the `UV` coordinates ourselves:

```
shader_type canvas_item;
uniform vec2 size;

void vertex() {
    UV = (VERTEX + (size * 0.5)) / size;
    VERTEX.y += sin(UV.y * 2.0 * TIME) * 10.0;
}

```

The uniform `size` should be set to the size of the sprite you want to match.

However, **this is not useful**, what we are getting from the shader is purely graphical. The physics server is unaware of it, and will not use it. Thus the motion generated from the shader will not cause collisions.

Most of the time not changing the `CollisionPolygon2D` is correct. That would make the animation purely visual. If purely visual is OK for you, then simply don't do this.

---

Alright, if we need to animate the `CollisionPolygon2D` in a way that works well with physics, how would we go about it?

As it turns out, if were to move or scale the `CollisionPolygon2D` without moving the `KinematicBody2D` collision may not register.

That also means that it is not useful to animate the `CollisionPolygon2D` using `AnimationPlayer`.

Speaking of `AnimationPlayer`, using it to animate the `KinematicBody2D` would work, but it is not ideal, because the animation would be absolute, and presumably we want to move `KinematicBody2D` from code.

Thus, we are going to solve this with GDScript.

---

Since we want the top of the `CollisionPolygon2D` and the `Sprite` to not move. Position them from the origin downwards (That is, do not have them centered to the `KinematicBody2D`). That will make the code much simpler.

I'll give you an initial version:

```
extends KinematicBody2D

func _physics_process(_delta):
    # other motion

    var time = OS.get_ticks_msec() / 1000.0
    scale.y = 1.0 + sin(2.0 * time) * 10.0 / ($Sprite.scale.y * $Sprite.texture.get_height())

```

Note that assuming that the `$Sprite.scale.y * $Sprite.texture.get_height()` we could replace it with a constant. For example, the default Godot icon.png is 64x64, assuming it is not scaled, we have `10.0 / (1.0 * 64.0)` which is `0.15625`.

```
extends KinematicBody2D

func _physics_process(_delta):
    # other motion

    var time = OS.get_ticks_msec() / 1000.0
    scale.y = 1.0 + sin(2.0 * time) * 0.15625

```

Something else, let us assume that we have some other motion that also changes the scale. To handle that you can keep track of how this motion affected the scale in a separate variable. For example:

```
extends KinematicBody2D

var old_scale:float = 1.0

func _physics_process(_delta):
    # other motion, for example scale.y += 0.001

    var time = OS.get_ticks_msec() / 1000.0
    var new_scale = 1.0 + sin(2.0 * time) * 0.15625
    scale.y += new_scale - old_scale
    old_scale = new_scale

```

Finally, if you want to see this motion on the editor, you could turn this into a `tool` script. You may have to close and open the scene again to take effect. However, if you do that, it will keep the scale it had at the moment you start the game. Thus, I suggest to reset the sacle on `_ready`. See Running code in the editor.
> 1 votes

---
Tags: collision-detection, godot, vertex-shader
---


# Question
Title: Constructing a building in the "Past" scene, and finding a different version of it in the "Future" scene
I am trying to create a game where one scene would be the "Past" and one scene would be the "Future". The player can travel through a portal to move between the past and future scenes.

In the past scene, the player makes a wooden house and in the future scene it will be turned into something else.

There can be multiple instances of these buildings in different places in the scene.

So far, I've tried...

1. Using `DontDestroyOnLoad` to carry the object through from the past to future when loading between scenes.
2. Using singletons to avoid duplicating the object multiple times when loading back and forth.

But that has a problem: using singletons causes restricts me to just one instance of the building per scene, and I want to have several.

The reason why I wouldn't want to unload the old object when the scene unloads is because I wanted the player to be able to build in any area available within the scene. Something like the Fallout 4 building mechanics, where you can build in certain areas and keep those buildings, but I want it to become a different prefab in the future scene.

How can I implement a feature like this?

# Answer
It sounds to me like what you want is something like a `BuildingManager` that keeps track of what has been built where.

When a new scene loads, the `BuildingManager` can look through its list of building placements, and spawn the appropriate prefabs for the current time period in those locations.

This could look something like this, using a `static` list to persist placement information between scenes/instances, and an `Awake` method that runs through that list and spawns appropriate prefabs.

You can place an instance of the `BuildingManager` in the scene for each time period, populating it with its date (so it knows which buildings to skip because they haven't been built yet / were already destroyed) and a list of prefabs so it knows what each building type should look like in its time period.

```
public class BuildingManager : MonoBehaviour {

    public struct Placement {
        public BuildingType buildingType;
        public Vector3 position;
        public Quaternion orientation;
        public int dateBuilt;
        public int dateRemoved;

        public Placement(BuildingType buildingType, Vector3 position,
                         Quaternion orientation, int date) {
            this.buildingType = buildingType;
            this.position = position;
            this.orientation = orientation;
            dateBuilt = date;
            dateRemoved = int.MaxValue;
        }
    }

    static List<Placement> _placements = new List<Placement>();

    [System.Serializable]
    public struct Builable {
        public BuildingType buildingType;
        public Transform prefab;
    }

    // Use this to set the time period for this scene, so you don't
    // show buildings that haven't been built yet, or buildings that
    // were removed in the past.
    public int date;

    // Populate this in the inspector with the list of prefabs
    // for each building type in this time period.
    public List<Buildable> buildables;

    // Call this to place a new building, and remember it for the future.
    public void Build(BuildingType buildingType, Vector3 position, Quaternion orientation) {
        if (Spawn(buildingType, position, orientation) == null )
            return;

        var placement = new Placement(buildingType, position, orientation, date);

        _placements.Add(placement);
    }

    // When the scene loads, spawn prefabs corresponding to each building placed.
    void Awake() {
        foreach (var placement in _placements) {
            if (placement.dateBuilt > date || placement.dateRemoved <= date) continue;

            Spawn(placement.buildingType, placement.position, placement.orientation);
        }
    }

    // Look up the right prefab for this building, and spawn it.
    // Return null if no prefab has been set up for this type.
    Transform Spawn(BuildingType buildingType, Vector3 position, Quaternion orientation) {

        int index = buildables.FindIndex(b => b.buildinType == buildingType);
        if (index < 0) {
            Debug.LogError($"No prefab assigned for the building type {buildingType}");
            return null;
        }

        return Instantiate(buildables[index].prefab, position, orientation);
    }
}

```
> 0 votes

---
Tags: unity, c#, 3d, scene
---


# Question
Title: Retrieve 3d models from a server in unity
I have 10 3d models which are about 8mb each..Now, should I store these 3d models in my apk or will it be wise to store it in a server and then retrieve it?.If so, how can I do that?

# Answer
> -1 votes
You can achieve this by using Asset Bundles in Unity https://learn.unity.com/tutorial/introduction-to-asset-bundles

this is the link to the official tutorial of unity describing to create asset bundles and load them from local path or a remote path

---
Tags: unity, 3d, server
---


# Question
Title: How to inspect child nodes in IDE debugger?
Consider an enemy with this node hierarchy:

```
* KinematicBody2D (Enemey)
|- Sprite
|- CollisionShape
|- Area2D (StompDetector)
   |- CollisionShape2D

```

With signal from `StompDetector` to `Enemy`:

```
func _on_StompDetector_body_entered(body: Node) -> void:
    if body.global_position.y < $StompDetector.global_position.y:
        die() ## >> BREAKPOINT <<

```

That does not work as exepcted. How to inspect `$StompDetector` from the debugger at `BREAKPOINT`?

# Answer
> 3 votes
On the debugger panel you will see the members variables of the current class/script and the local variables of the current function. The node you want is neither. Thus a solution is to store it in a variable.

However, if you want to access a different node while debugging there is another way…

While debugging, you can go to the Scene panel (on the top left of the editor by default), and you will see two tabs:

* **Local**: contains the scene tree for editing (which is what you have access normally).
* **Remote**: contains the current scene tree of the game that is running.

Use the Remote tab to get to nodes you want. When you select them, their current state will appear on the inspector panel (on the right of the editor by default).

---
Tags: godot, debugging
---


# Question
Title: Unity - Make a Mirror character of player in movement
What I want to achieve is :

* I have a 3D game - with player in third person - and using cinemachine Camera - imagine it like PUBG where you can look any where - the direction of the player does not change until the player is moving - the direction of character change in the same direction as camera
* I want to make some sort of Shadow character as enemy , it will face the player - and mimic every movement exactly - not harmful
* so when the player move forward - the other copy also move toward player - thus blocking his movement

so I want to achieve this using RigidBody - as Physics is needed to solve this puzzle

I tried different approaches- until I got to this code - it works OK - until I change the camera direction and then every thing is not working any more

```
     public Transform cam ;

    float speed = 10f;    //How fast the player can move
    float turnSpeed = 100;    //How fast the player can rotate

   public Animator animator; //Animation Control
    Rigidbody rigidBody; //Make sure you have a rigidbody

    void Start()
    {
        //Initialize appropriate components
        animator = GetComponent<Animator> ();
        rigidBody = GetComponent<Rigidbody>();
        cam = Camera.main.transform;
    }

    //No need for update function right now, physics work better in Fixed Update

    void FixedUpdate()
    {
        //right is shorthand for (1,0,0) or the x value            forward is short for (0,0,1) or the z value
        Vector3 dir =  (-cam.forward * Input.GetAxis("Vertical"))+ (cam.right * Input.GetAxis("Horizontal")) ;

        dir.y = 0;//Keeps character upright against slight fluctuations

        if (Input.GetAxis("Horizontal") != 0 ||Input.GetAxis("Vertical") != 0)
        {
                                                   //rotate from this /........to this............../.........at this speed
            rigidBody.rotation = Quaternion.Slerp (transform.rotation, Quaternion.LookRotation (dir), turnSpeed * Time.deltaTime);
            rigidBody.velocity = transform.forward * speed;
            animator.SetFloat ("Blend", 10);//Walk or run Blend works well here
        } else
        {
            rigidBody.velocity = new Vector3(0,0,0).normalized;
            animator.SetFloat ("Blend", 0);//Idle Blend works well here
        }
    }

    }

```

# Answer
Use `Vector3.Reflect(...)` function to get a movement vector for the enemy that is a reflection of the player's movement vector.
First argument of the function is your player movement vector, in your case it should be `rigidBody.velocity`.
The second argument is a vector that represents the normal of the plane from which the player's vector will be reflected. You'll need to decide what will be the 'mirror' plane for the reflection and use a vector that points out from the mirror plane.
I think you could use a direction vector that points from the enemy to the player as the mirror normal vector, so the enemy's movements won't depend on neither the camera direction nor the direction the player's model is looking at.
So, something like this:

```
Vector3 dirToPlayer = player.position - enemy.position;
dirToPlayer.Normalize(); // the normal vector should have magnitude 1 so the distance between the enemy and the player won't affect the reflection results.
Vector3 reflectedVector = Vector3.Reflect(playerRigidBody.velocity, dirToPlayer);
enemyRigidBody.velocity = reflectedVector;

```
> 0 votes

---
Tags: unity, 3d
---


# Question
Title: Moving the bulk of a recursive ray tracer function to the gpu, using DirectX12 not DirectX 12 DXR HLSL
So I'm wanting to generate images by ray tracing. I've done so, but the main ray function is recursive. I know one can make a non recursive function out of a recursive function using a stack, but is it possible to do in HLSL? I have the bulk of the function I'm using here:

```
color ray_color(
    const ray& r,
    const color& background,
    const hittable& world,
    const shared_ptr<hittable>& lights,
    int depth) {

hit_record rec;

// If we've exceeded the ray bounce limit, no more light is gathered.
if (depth <= 0)
    return color(0, 0, 0);

// If the ray hits nothing, return the background color.
if (!world.hit(r, 0.001, infinity, rec))
    return background;

scatter_record srec;
color emitted = rec.mat_ptr->emitted(r, rec, rec.u, rec.v, rec.p);

if (!rec.mat_ptr->scatter(r, rec, srec))
    return emitted;

if (srec.is_specular) {
    return srec.attenuation
        * ray_color(srec.specular_ray, background, world, lights, depth - 1);
}

auto light_ptr = make_shared<hittable_pdf>(lights, rec.p);
mixture_pdf p(light_ptr, srec.pdf_ptr);
ray scattered = ray(rec.p, p.generate(), r.time());
auto pdf_val = p.value(scattered.direction());

return emitted
    + srec.attenuation * rec.mat_ptr->scattering_pdf(r, rec, scattered)
    * ray_color(scattered, background, world, lights, depth - 1)
    / pdf_val;
}

```

# Answer
So I was under the mistaken assumption that a ray needs to be generated recursively, also that it would need to keep track of branching. I understand now that I can just send a single ray out at a time and test for hits without recursion. The pdf, probability distribution function, fidgets with the ray to take other paths I'm pretty sure.
> 0 votes

---
Tags: hlsl, raytracing, directx12
---


# Question
Title: How to create a texture SRV with different sRGB format from a render target in DX11?
Is it possible to bind a texture with a different format as render target and as shader resource view?

Specifically with a different \_SRGB suffix. My goal is to render a shader into an R8G8B8A8\_UNORM texture but read the render target in another shader as R8G8B8A8\_UNORM\_SRGB, or the other way around. Basically controlling on the read and write side whether automatic sRGB conversion should happen. There is no window or swap chain involved.

So far, I get an invalid args exception when I try to create a texture view with a different format. I am using the Stride game engine set to Directx 11 graphics API, which uses SharpDX.

# Answer
Direct3D supports 'type re-casting' within limits.

You typically have to first create the resource as 'typeless' which in this case would be `DXGI_FORMAT_R8G8B8A8_TYPELESS`:

```
CD3D11_TEXTURE2D_DESC desc(
        DXGI_FORMAT_R8G8B8A8_TYPELESS,
        width, height,
        1, // The render target view has only one texture.
        1, // Use a single mipmap level.
        D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE,
        D3D11_USAGE_DEFAULT,
        0,
        1
    );

DX::ThrowIfFailed(device->CreateTexture2D(
    &desc,
    nullptr,
    &m_renderTarget));

```

Create the RTV as `DXGI_FORMAT_R8G8B8A8_UNORM`:

```
CD3D11_RENDER_TARGET_VIEW_DESC rtvDesc(
    D3D11_RTV_DIMENSION_TEXTURE2D,
    DXGI_FORMAT_R8G8B8A8_UNORM);

DX::ThrowIfFailed(device->CreateRenderTargetView(
        m_renderTarget.Get(),
        &rtvDesc,
        &m_renderTargetView));

```

Then create the SRV as `DXGI_FORMAT_R8G8B8A8_UNORM_SRGB`:

```
CD3D11_SHADER_RESOURCE_VIEW_DESC srvDesc(
    D3D11_SRV_DIMENSION_TEXTURE2D,
    DXGI_FORMAT_R8G8B8A8_UNORM_SRGB);

DX::ThrowIfFailed(device->CreateShaderResourceView(
    m_renderTarget.Get(),
    &srvDesc,
    &m_shaderResourceView));

```

> Note that there are some special conditions when using SRGB for backbuffers. See this blog post series.
> 1 votes

---
Tags: textures, directx, sharpdx, srgb, stride
---


# Question
Title: Does friction only apply in opposite direction of motion?
Let's say an object is sliding on a slope and is the object has a velocity of (0,0,5). The friction would be acting in the opposite direction of motiong, being (0,0,-1).

However, gravity is also affecting the object on the slope. The gravity is doing an impulse of (-1,-1,0) every frame in the direction of the slope tangent. Should the object also experience friction in the direction of (1,1,0)? Or would it only experience friction in the direction of (0,0,-1)?

I find the notion that friction always opposes the direction of motion strange, because this means that when an object is sliding downwards slightly on a slope, but not much, due to friction acting in opposite direction of gravity, when you add an impulse in a perpendicular direction, suddenly the object will be sliding downwards much more because friction is no longer resisting gravity. Is that correct?

# Answer
> 0 votes
Friction is directly related to velocity.
Gravity and other forces might cause an object to accelerate, changing its velocity, so they indirectly affect friction.
But they do not appear in the friction equation, for example in the simplest case you have:

\\$ \vec{F} = k.\vec{v} \\$ with \\$k\\$ a constant depending on the object's and contact surface's properties.

However, in more complex models, the coefficient \\$k\\$ can also depend on the normal force at the surface, which is itself proportional to the object's weight.

# Answer
> 0 votes
Friction acts in the opposite direction of the force vector. When gravity is the only force acting on the box, friction is in the opposite direction of gravity. Adding an impulse perpendicular to gravity does not negate gravity or the friction acting against it on the plane of the slope, it simply adds another component to the force vector. Add all force vectors together and then subtract the friction.

---
Tags: physics
---


# Question
Title: WebGL game won't go into fullscreen mode on iOS devices
I have built my game and hosted it on itch.io. it works well on PC browsers and on the mobile Android browser.

The problem appears when I try to launch it on an iOS phone: the game won't go into full screen (it's supposed to go into it automatically). I added a button that's supposed to switch to full screen but it doesn't respond (the button does work on PC and Android though).

# Answer
It looks like you've encountered a limitation of Safari for iOS, where the Fullscreen API is largely unsupported, being usable only for iPad devices running iOS 12 or later (MDN, caniuse).

Safari users on iPhone and iPod devices will be unable to take advantage of true fullscreen functionality, though you can get quite close by prompting users to add your web application to their home screen and applying specific `<meta>` tags to your page. You'll also want your game to span the entire content of the web page. From the great answer here:

```
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<meta name="viewport" content="viewport-fit=cover, user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">

```

Outside of the above, one can reduce the visibility of Safari UI – completely hiding it when in landscape – through certain interactions such as scrolling. See this answer for more details on how to make clever use of this. (Previously this could be done programmatically, though Apple's patched that option for now.)

---

**Note:** in the past, this functionality could be enabled for iPhone/iPod devices through Safari's advanced settings pane (Settings \> Safari \> Advanced \> Experimental Features \> Fullscreen API), though this is unfortunately no longer the case.

**Related, somewhat dated (iOS 6) question:** https://stackoverflow.com/questions/12822739
> 2 votes

---
Tags: unity, ios, unity-webgl
---


# Question
Title: Pulling chain/rope up and updating the path of the chain
I am trying to update the path of a chain (currently being stored in my code as a array of points) by moving one end of it up. I need the start of the chain to remain fixed in its location and the end up will be moving upwards.

The chain is a series of links that are rigid and have roughly 20-30 degrees of available bend/movement between each link. The array of points is ordered so that the first entry is the point that will be moving up, and the last point is fixed.

I started by creating the chain in its default state:

I've created a method `moveUp` that takes in the points, how high to move the last point up to and a step for how much movement per iteration of the loop defined in the method. My logic for the method is basically:

1. Loop until the first point has reached the correct height
2. If it's the very first point, just move it up by `step`
3. If the distance between the previous point and next point is `step` then I break the loop.
4. If the distance between the previous point and the next point is greater than `step*2` then I move the point to be a distance of `step` from the previous point
5. If the distance between the previous and next is less than `step*2` then I create a circle on previous and next with a radius of `step` and use the intersection of these circles to find where to move the point to. (since there can be 2 intersects, I just pick the one that is closer to the original point). Once this step has ran I tell the loop to break after updating the point, since everything after that should not need to move.

Until the chain uncoils a bit on the right side, everything works:  But once I go much more then this, the chain starts to "pull away" from the fixed point on the left:

How can I update my logic/method to make it so this won't pull away from the fixed point and give me a decent looking path for my chain? Here is the code below for the moveUp method (note this uses a custom programming language, so if something is not clear in the below snippet, let me know I can clarify):

```
private point2D[] moveUp( point2D[] original, double height, double step=0.75inch ) {
    if ( original.any() ) {
        int count = 0;
        while( height - original.first.y >= step ) {
            count++;
            if ( count > 100 ) {
                pln("Too many iterations...");
                break;
            }
            bool shouldStop = false;
            for( p in original, index=i ) {
                point2D old = p;

                if ( i=0 ) {
                    p = p + (0,step);
                } else {
                    if ( !last ) {
                        point2D prev = original[i-1];
                        point2D next = original[i+1];

                        line2D l( prev, next );

                        if ( l.length() == step ) {
                            break;
                        } else if ( l.length() > step*2 ) {
                            l.extendP0(-step);
                            p = l.p0;
                        } else {
                            circle prevC( prev, 0.75inch );
                            circle nextC( next, 0.75inch );

                            var intersect = this.ins(prevC,nextC);

                            if ( intersect.count == 0 ) {
                                pln("No intersection found...".eAngry);
                            } else {
                                point2D choice = intersect.p0;
                                if ( intersect.count > 1 ) {
                                    double distP0 = p.distance(choice);
                                    double distP1 = p.distance(intersect.p1);
                                    if ( distP1 < distP0 ) {
                                        choice = intersect.p1;
                                    }
                                }

                                p = choice;
                                shouldStop = true;
                            }
                        }
                    }
                }

                original[i] = p;
                if ( shouldStop ) { break; }
            }
        }
    }

    return original;
}

```

# Answer
You need to consider how your algorithm handles **tension** in the chain — when it's stretched, what happens?

> If the distance between the previous point and the next point is greater than `step*2` then I move the point to be a distance of `step` from the previous point

This element of the algorithm always favors "previous" points. The last point never gets to contribute any "force" towards itself, so all the other points pull away from it.

Instead, try moving the point to be at the *midpoint* between the adjacent points. This will give a closer to realistic result.

---

Another factor causing asymmetry in your algorithm is that when you are checking the points' positions, the "previous" point is always one that *has already been updated*, and the "next" point is always one that *has not yet been updated.*

To fix this, don't assign to the points in `original` — only *read* positions from it, and use a separate array to return the new positions. Thus, the order in which you compute the points' updates doesn't affect the result.
> 2 votes

---
Tags: rope-physics
---


title: What does a Vector3 state?

text:
# Question
Title: What does a Vector3 state?
I'm really stucked. I couldn't understand what does `Vector3` state.

When I look Unity Vector3 documentation it says

> Representation of 3D vectors and points.

According to this sentence, a `Vector3` can state a point or a vector in space.

But When I go into other documentation about `Vector3` it really confused me.

For example When I look `Vector3 Constructor` documentation it says

> Creates a new vector with given x, y, z components.

So that means `Vector3` states a vector.

But When I look `Debug.DrawLine(Vector3 startpoint, Vector3 endpoint)` it says startpoint and lookpoint are points in world space. So according to this, Vector3 is a point not a vector

I can increase the examples.

For example when I go into `transform.position` documentation it says,

> The world space position of the Transform.

So it says Vector3 is a position(that means point. I think you can't state a position with Vector)

But when we try to change a position of gameobject with `transform.position` we again use `Vector3` and that state a vector.Because you can't change position of a gameobject with point. You could use Vector

So, what does a `Vector3` state ?

# Answer
A `Vector3` is a set of 3 float values: x, y, and z. These 3 values can represent whatever you want, but usually are used to represent the three axes of either a **position**, a **vector**, or a **euler rotation**.

You generally should be able to tell what a `Vector3` represents from context/variable naming. It's important to make the context clear, to avoid mistakes like this:

```
Vector3 a = transform.position;
Vector3 b = transform.eulerAngles;
a += transform.forward * speed * Time.deltaTime;
b += rotationSpeed * Time.deltaTime;
//oops, we mixed these up! we should have used better variable names!
transform.position = b;
transform.eulerAngles = a;

```

Your question is analogous to asking "what does a float represent"? A float simply stores a floating-point value; it isn't inherently a distance or a speed or a time or a weight or any other specific type of unit. The meaning of the value is taken from context, e.g.

```
float distance = Vector3.Distance(point1, point2);
float time = Time.time;
float speed = 5.5;

```
> 1 votes

---
Tags: unity, vector
---


# Question
Title: I want to use the GameJolt API, how do I protect my private key which is in my game?
GameJolt is a gaming platform/website that offers API access with features like achievements tracking for users, etc. I can use the API no problem on my tests but what I'm concerned about is the private key that is issued to my game. How do I ensure that it's protected from people that want to decompile my game? Once they get the API private key, they will be able to do anything with it.

# Answer
This question has actually been asked several times, and the answer is always the same thing; you're not going to like it. ***It's impossible to keep things like this a secret.*** You can however, take measures to make it more difficult for your passwords to be discovered. Essentially, you could convert it to a byte array and then perform some kind of hashing algorithm on the bytes. This can also be reversed by anyone with enough time and patience, but so can anything else. What you're basically trying to do is *increase the amount of time required to discover the internal passwords*. If the time required is greater than what the "hacker" is willing to spend, they will fail, and your game will remain secure. An example of fairly simple byte encryption is as follows:

```
using System;
using System.IO;
using System.Text;

namespace Your.Engine.Framework
{

    public class Obfuscator
    {
        private int _inext;
        private int _inextp;
        private int[] _seedArray = new int[56];
        private int _seed;

        public int Seed
        {
            get
            {
                return _seed;
            }
            set
            {
                _seed = value;
                int subtraction = (_seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs(_seed);
                int mj = 0x9a4ec86 - subtraction;
                _seedArray[0x37] = mj;
                int mk = 1;
                for (int i = 1; i < 0x37; i++)
                {
                    int ii = (0x15 * i) % 0x37;
                    _seedArray[ii] = mk;
                    mk = mj - mk;
                    if (mk < 0x0)
                    {
                        mk += Int32.MaxValue;
                    }
                    mj = _seedArray[ii];
                }
                for (int k = 1; k < 0x5; k++)
                {
                    for (int i = 1; i < 0x38; i++)
                    {
                        _seedArray[i] -= _seedArray[1 + (i + 0x1e) % 0x37];
                        if (_seedArray[i] < 0)
                        {
                            _seedArray[i] += Int32.MaxValue;
                        }
                    }
                }
                _inext = 0;
                _inextp = 21;
            }
        }
        public Obfuscator()
        {

        }

        public Obfuscator(string seed)
        {
            SetSeed(seed);
        }

        public Obfuscator(int seed)
        {
            SetSeed(seed);
        }

        public void Reset()
        {
            this.Seed = this.Seed;
        }

        public void SetSeed(string seed)
        {
            this.Seed = GenerateHashCode(seed);
        }

        public void SetSeed(int seed)
        {
            this.Seed = seed;
        }

        private static unsafe int GenerateHashCode(string data)
        {
            fixed (char* str = data)
            {
                int num = 0x15051505;
                int num2 = num;
                int* numPtr = (int*)str;
                for (int i = data.Length; i > 0; i -= 4)
                {
                    num = (((num << 0x5) + num) + (num >> 0x1f)) ^ numPtr[0];
                    if (i <= 2)
                    {
                        break;
                    }
                    num2 = (((num2 << 0x5) + num2) + (num2 >> 0x1f)) ^ numPtr[1];
                    numPtr += 2;
                }
                return (num + (num2 * 0x5d588b65));
            }
        }

        private int NextOffset()
        {
            int locINext = _inext;
            int locINextp = _inextp;
            if (++locINext >= 56)
            {
                locINext = 1;
            }
            if (++locINextp >= 56)
            {
                locINextp = 1;
            }
            int retVal = _seedArray[locINext] - _seedArray[locINextp];
            if (retVal == Int32.MaxValue)
            {
                retVal--;
            }
            if (retVal < 0)
            {
                retVal += Int32.MaxValue;
            }
            _seedArray[locINext] = retVal;
            _inext = locINext;
            _inextp = locINextp;
            return retVal;
        }

        public byte[] TransformString(string data)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(data);
            TransformBytes(bytes);
            return bytes;
        }

        public void TransformFile(string inputPath, string outputPath)
        {
            byte[] inputBytes = File.ReadAllBytes(inputPath);
            TransformBytes(inputBytes);
            File.WriteAllBytes(outputPath, inputBytes);
        }

        public void TransformBytes(byte[] bytes)
        {
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = (byte)(bytes[i] ^ NextOffset());
            }
        }
    }
}

```

The above C# code was written for my game engine. It uses an XOR cipher and an inlined Random class. You take the password's GetHashCode(), run an xor cipher on using the hashcode on each byte, and then store the resulting byte array somewhere in your executable. In order for someone to decompile your password, they will need to first decompile this class successfully, figure out how it works, and just generally do a lot of work to convert everything. Using actual Obfuscation will greatly increase the time further, because the binaries will be simplified down to single letter variables, functions, and class names. It will lose all coherency, which will make it extremely difficult for someone to figure out what's going on.
> 4 votes

# Answer
A simple key based software solution is insufficient to solve this problem.

Even if you obfuscate the key, people can easily wait until you generated the key, stop the execution, and grab it from memory. Obfuscation of keys is only relevant in scenarios where attackers fully automate the extraction, e.g. to switch the key for in app payments before they re-release your game under their name.

If creating a user involves some kind of cost, you can try to detect and resolve compromised instructions on the server side, and ban offending user ids, but that's it.

Also, don't use the GameJolt global data storage, unless you want random players to wipe information provided by other players. Stick to the per-user features.
> 1 votes

# Answer
One way I handled this in the past was to relay API requests via my own server.

Instead of contacting the API service directly, my game would send a request to my server. My server could then validate the request, perform rate-limiting, etc.

Then, if it determined the request was valid and in-budget, it would generate the appropriate query to the actual API service, signing it with my API key. Then it would reply back to the game client with the relevant results.

This way, my API key lived solely on my own server under my control. Someone decompiling my game would not be able to send arbitrary API requests under my name, because the key is nowhere inside the client.

They could still spoof my client to route similar messages to my server, but at least I could control the set of operations they could ask to do that way, and block off parts of the API that I did not want to use, because my server offered no endpoint for it. I could also restrict the volume of requests so that one hacker trying to scrape my data couldn't use up all my API allotment or impact other players' ability to access it.

With appropriate logging, this can also give you the ability to detect malicious use from a hacked client, analyze its patterns, and update your server to block or send false results to clients matching that pattern, if you're particularly concerned about targeted misuse like this.
> 0 votes

---
Tags: security
---


# Question
Title: How can I access a method via a string in Unity?
I myself am new to unity and I would like to know how it is possible to access a method via a string, something like this:

```
public string PlayerPrefsName;

public GameObject Button;

public string GadgetForSkin;

private void Start()
{
    GadgetChanged = PlayerPrefs.GetInt(PlayerPrefsName);
    if (GadgetChanged == 0)
    {
        Button.SetActive(false);
    }
    GadgetForSkin = "GadgetForSkin" + GadgetChanged;
}

public void GadgetChecker()
{
    GadgetForSkin();
}

public void GadgetForSkin1()
{

}

```

If it's not possible, how can I achieve something similar?

# Answer
You can do this with MonoBehaviour.Invoke or GameObject.SendMessage, like so:

```
Invoke(GadgetForSkin, 0f);             // Calls method on the next frame's update.
// Or
gameObject.SendMessage(GadgetForSkin); // Calls method on every script on this object.

```

...but I would recommend strongly against using these in a modern project.

We have much better options now that don't result in "stringly-typed" code or costly reflection and search in the middle of your gameplay code.

Instead I'd recommend doing something like this...

```
[System.Serializable]
public struct Gadget {
    public string name;
    public Sprite icon;
    public UnityEvent onUse;
}

public Gadget[] gadgets;

int selectedGadget;

public void UseSelectedGadget() {
    gadgets[selectedGadget].onUse.Invoke();
}

```

This gives you a handy list of gadgets you can configure in the inspector, setting up the name/icon or other properties each one might need, and also lets you hook up any number of functions to call when the gadget is used. No mucking with strings required (and no garbage created from said string mucking).

You could even use one of the `UnityEvent<T>` options if you want to pass arguments to your gadget methods. That might help you avoid duplicated code. Say you have 4 different "grenade" gadgets that differ only in the elemental type of damage they do. You could pass that damage type as an argument, and have all 4 grenade gadgets call the same `UseGrenade(DamageType damageType)` function with their own arguments configured in the inspector, instead of needing a separate `FragGrenade()`, `FrostGrenade()`, `LightningGrenade()`, etc.
> 2 votes

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


# Question
Title: Would creating a player scriptable game using Unreal Engine or Unity violate their license agreement?
I want to create a game in Unity or UE4 which allows the user to write scripts in Python and run them mainly to control the AI. I will have to find a way to enable runtime script execution first. After searching the internet i was able to find some ways that may work.
What i cant find an answer for is how to limit the parts of engine and game code the user has access to so that the player doesnt feel like he's playing it in God mode.
And the main question is that even if i am able to restrict access to the API will it violate the terms of agreement for these commercial engines because the player will get access to the underlying engine and will be manipulating objects within it. I don't intend to make a moddable game just a game that requires you to write some code but that would be an extreme case to think about.

# Answer
If you're using the Unity engine and add AI scripting support with Python, that doesn't inherently give players "access to the underlying engine". The only way you'd be giving "access to the underlying engine" is if you made a Python wrapper that could access substantial portions of the Unity API, which would be a nightmare to implement. AI scripting does not inherently need such a wrapper.

However, as Vaillancourt noted in his comment, Lua is most likely a better choice for scripting that can be modified by end-users.
> 1 votes

---
Tags: unity, unreal-4, python, scripting, licensing
---


title: Are polygon normals really shadeable?

text:
# Question
Title: Are polygon normals really shadeable?
*Garry's Mod* has a copy-protection trap that shows this error:

> Unable to shade polygon normals

It made me wonder if such a problem could ever *actually* exist. Can polygon normals be shaded? Is a failure to do so detectable and reportable?

# Answer
"Can a polygon normal be shaded" - No, a normal is a vector which is a 1-d object, so unless you're going to actually draw the normal and shade it, that statement doesn't make much sense.

However, shading polygons (2-d objects) commonly use the polygon normal in their shading calculations for light calculations to control how light or dark they can be.

So, I have no idea what that message is trying to say.
> 3 votes

# Answer
Normals in 3D graphics are a 3D vector indicating orientation or direction.

Normals themselves cannot be shades, as how can you shade {.1,0,.4} ?

Normals can be used to shade the polygons themselves. For example, a light source at a certain angle hitting a model made of polygons at a certain angle, the normals of the polygon faces can be used in the shading process to make the light make parts of the model brighter.
> 5 votes

# Answer
It's 100% not possible to shade a normal at all.

As discussed in this link from the comments, the message was chosen to stop people from being able to research it, to tempt them into asking about it, and outing themselves as pirates.

This was counting on players not knowing what a polygon normal actually was. :)
> 2 votes

---
Tags: 3d, graphics, terminology
---


# Question
Title: SteamVR No Longer Opening With Unity Projects
I'm trying to get Unity to open/utilize SteamVR for development. Everything was working fine until today, but now Unity does not use SteamVR.

I did not make any changes to SteamVR recently, and I get the same results on multiple projects and Unity installs. I also tried rebooting.

It looks like Windows pushed an update today for KB4023057 but I can't uninstall it. It's not found within uninstall updates, not in add/remove programs, and even using command prompt wusa /uninstall /kb:4023057 results in "KB4023057 is not installed." So it seems I'm stuck with it.

Any other ideas to either try to uninstall the update or else to somehow get SteamVR working in Unity again?

# Answer
I compiled the code and ran it outside the Unity Editor and it actually connected to VR. Then, after that, it started connecting via the Unity Editor again. Bizarre!
> 0 votes

---
Tags: unity, windows, steam-vr
---


# Question
Title: How to Get VR Controller's Velocity in Unity with SteamVR?
Back when I used Unity 2017 and controller bindings weren't a thing, I simply attached a rigidbody to my Vive controller and read out the velocity of the rigidbody to know how fast the player was swinging the controller. Now, I've updated to Unity 2021.2.0a14, I went through all the effort of modifying my code to work with bindings, and it doesn't seem like I can get velocity anymore. The rigidbody always reports zero velocity. I can see the World Center of Mass vector changing so I know it registers motion, but it's just not reporting the velocity anymore. Is there a new setting in Unity I need to turn on to measure things that it doesn't personally control? Or do the new bindings options have a way to get velocity as an input? Am I forced to calculate it myself now? Thanks!

Edit: Base assumption was wrong, I did not get velocity from the rigidbody attached to the hand controller like I thought I did. I got it directly from SteamVR\_Controller. So Unity is probably acting like it ever did.

# Answer

    public SteamVR_Action_Pose PoseAction; //initialized via inspector to a pose action
    public SteamVR_Input_Sources controller; // also initialized via inspector

    public void Start()
    {
        PoseAction.AddOnUpdateListener(controller, PoseUpdate);
    }

    public void PoseUpdate(SteamVR_Action_Pose fromAction, SteamVR_Input_Sources fromSource)
    {
        Debug.Log(fromSource.velocity);
    }
```

> 0 votes

---
Tags: unity, rigidbody, steam-vr
---


# Question
Title: Combining mesh on the fly without using gameObject
I procedurally generate chunks and use the marching cube algorithm to create meshes in 3D. At first, I just created a gameObject for each cube (of course, I knew it was not optimized, but I wanted to see if the algorithm worked). For now I stock all gamesObject in child of "blocks" but it would be much more optimized to directly merge the meshes between them and only create a single gameObject. However, i did not find any way to directly merge the meshes between them.
So my question is: is there a way to directly merge meshes between them without having to use gameObject? (don't worry about texturing)

Here's the code:

```
    public static GameObject GenerateChunk(int[,,] map, int chunkSize, Vector3 chunkPosition)
    {
        GameObject blocks = new GameObject("BlockList");
        GameObject newMesh;
        int[] cubeVertices = new int[8];

        // create each mesh in a gameObject as child of "blocks"
        for (int x = 0; x < chunkSize; x++)
            for (int z = 0; z < chunkSize; z++)
                for (int y = 0; y < chunkSize; y++) {
                    /*
                    define the vertices (cubeVertices)
                    */
                    Vector3 cubePosition = new Vector3(chunkPosition.x + x, chunkPosition.y + y, chunkPosition.z + z);
                    newMesh = GenerateCube(cubePosition, cubeVertices);

                    if (newMesh != null)
                        newMesh.transform.parent = blocks.transform;
                }

        //combine every children of "blocks" and delete them
        MeshFilter[] filters = blocks.GetComponentsInChildren<MeshFilter>();
        List<CombineInstance> combine = new List<CombineInstance>();
        for (int i = 0; i < filters.Length; i++) {
            if (filters[i].sharedMesh == null)
                continue;
            for (int j = 0; j < filters[i].sharedMesh.subMeshCount; j++) {
                CombineInstance ci = new CombineInstance
                {
                    mesh = filters[i].sharedMesh,
                    subMeshIndex = j,
                    transform = filters[i].transform.localToWorldMatrix
                };
                combine.Add(ci);
            }
            Destroy(filters[i].gameObject);
        }

        //create the chunk and set the final mesh with the CombineMeshes function
        GameObject chunk = new GameObject("Chunk", typeof(MeshFilter), typeof(MeshRenderer));
        chunk.GetComponent<MeshFilter>().mesh.CombineMeshes(combine.ToArray(), true, true);
        Destroy(blocks);
        return chunk;
    }

```

# Answer
> 1 votes
Your code shown here doesn't actually depend on GameObjects - they're just serving as an expensive way for you to store a set of positions. So you could get something equivalent as follows, just using transformation matrices instead:

```
// You can assign the default Unity cube here so you have a template mesh to stamp-out.
public Mesh cubeMesh;

public static Mesh GenerateChunkMesh(int[,,] map, int chunkSize, Vector3Int chunkPosition)
{
    // Prep a list of mesh instances to stitch together.
    List<CombineInstance> instances = new List<CombineInstance>();

    // Prepare a "template" object with the attributes we want to apply to each block.
    CombineInstance instance;
    instance.mesh = cubeMesh;

    for (int x = 0; x < chunkSize; x++)
        for (int z = 0; z < chunkSize; z++)
            for (int y = 0; y < chunkSize; y++) {
                Vector3Int cubePosition = chunkPosition + new Vector3Int(x, y, z);

                // If this part of the map is empty, skip it without making a block.
                if(map[cubePosition.x, cubePosition.y, cubePosition.z] == 0)
                    continue;

                // Make a transformation matrix that positions the cube at this location.
                instance.transform = Matrix4x4.Translate(cubePosition);

                // Record "I want a cube at this position" in our work list.
                instances.Add(instance);
            }
        }
    }

    // Build a mesh that combines all of the requested cubes in our work list.
    var mesh = new Mesh();
    mesh.CombineMeshes(instances.ToArray(), true, true);

    return mesh;
}

```

But note that this is still rendering more geometry than you need, because you're not eliminating hidden faces. This answer outlines how you can do that with your own mesh generation routine.

# Answer
> 0 votes
ps: This is an answer for someone using marching cubes algorithm WITHOUT using Chunks. I tried the precedent solution for marching cubes but without chunks, and `instance.transform = Matrix4x4.Translate(cubePosition);` makes my every little cubes distanciated a bit, so to solve this, i used instead `instance.transform = transform.localToWorldMatrix;` whichi i found in the unity documentation example. Hopes, this helps someone :)

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


# Question
Title: Circular draggable UI element in Unity canvas
I am trying to implement my own runtime color picker that's easy to use for touch interfaces. I want the hue slider to be a ring, along these lines, except the whole ring texture would rotate when dragged.

I have scavenged enough code to get a raw image object rotating when dragged in a UI canvas in the manner I'm looking for:

```
    private float baseAngle;
    private Vector2 pos;

    public void OnBeginDrag(PointerEventData eventData)
    {
        pos = transform.position;
        pos = eventData.pressPosition - pos;
        baseAngle = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg;
        baseAngle -= Mathf.Atan2(transform.right.y, transform.right.x) * Mathf.Rad2Deg;
    }

    public void OnDrag(PointerEventData eventData)
    {
        pos = transform.position;
        pos = eventData.position - pos;
        float ang = Mathf.Atan2(pos.y, pos.x) * Mathf.Rad2Deg - baseAngle;
        transform.rotation = Quaternion.AngleAxis(ang, Vector3.forward);
    }

```

Since it doesn't use colliders, how can I limit the draggable region to a circle within the square bounds of the texture? Even better, also limit it to a ring rather than a whole circle. Will I have to implement my own check based on some pure math or is there a built in way?

thanks!

# Answer
You should consider how this detection can be achieved fundamentally, then search if this solution already exits in Unity engine.

• If I couldn't find anything specific - I would use a polygonal 2D/3D collider (may require a rigidbody). Or I would use 2 circle colliders in your case.

• If I had to write my own detection - I would use just simple radius calculations, first I would define min/max radius, then detect collision by using internal methods for UI collision which would give me the object I need, and the last step would be to calculate my mouse position relative to min/max radius that I have and to determine if it's inside these bounds.

*My Comment: EventSystem should raycast UI, you can check if the object currently being raycasted is the one you need, but it's probably going to raycast whole image and not just sprite, so it might not work. In that case you need your own system I guess. Thing is - think about ways a computer can detect collision in sprites, if it's not possible then it's probably not in the game engine. If you come to conclusion that it needs colliders or pixel value detection then use those. See if you can have polygonal colliders for sprites. Another way would be to block areas inside and outside from raycasting.*
> 0 votes

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


# Question
Title: How can I serialize lists to JSON on mobile?
I'm having difficulties serializing lists with the built in JsonUtility. I eventually figured out this just isn't possible with its limited capabilities.

As much as I'd like to use Newtonsoft, I cannot use that either because this is a mobile game, and from what I understand it doesn't work on Android or iOS.

Does anyone have any suggestions for how I can serialize my lists on mobile? I don't want to have to use hacky solutions to get these lists in and out of JSON.

# Answer
To be able to serialize some data using Unity's built in serializer, you will have to contain your data in a class. You can't simply serialize a list as is.

Something like this should work. You can make some sort of generic class like here, if you only need to serialize lists containing different types of data:

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

public class SerializationDemo : MonoBehaviour
{
    [SerializeField] List<string> yourList;

    void Start()
    {
        // Your list with some data
        yourList = new List<string> { "foo", "bar" };

        // Store your data into a container class,
        // this can be serialized
        var data = new SaveData<string>(yourList);

        // Class contents to json using Unity's serializer
        var jsonText = JsonUtility.ToJson(data);

        // Save your json data here instead of logging it...
        // JSON: {"list":["foo","bar"]}
        Debug.Log("JSON: " + jsonText.ToString());
    }
}

[System.Serializable]
public class SaveData<T>
{
    public List<T> list;

    public SaveData(List<T> data)
    {
        this.list = data;
    }
}

```
> 1 votes

# Answer
The JSON.NET plugin for Unity officially supports "all Unity platforms including WebGL, except for WebPlayer, Windows 8.0 and Windows Phone 8.0."
> 1 votes

---
Tags: unity, mobile, serialization, json
---


title: Combining cubes Issue in Marching Cubes

text:
# Question
Title: Combining cubes Issue in Marching Cubes
I was trying to implement the marching cubes and combine every little cube this way:

* I get a cube of vertices depending on their surfaceLevel
* I look for the ones that are below the surfaceLevel and get the edges that relates to them
* get a vertice out of the edge using the formula on: http://paulbourke.net/geometry/polygonise/
* I put every vertex i created based on the edges on mesh.vertices
* I make the order on mesh.triangles based of the edge number on triTable
* i combine everything but i get this:

Here's my code: https://pastebin.com/jqetCk8r. My guess was that the combine order of every marched little cube is not good. I've got no idea know how to solve this.

ps: the triTable doesn't show in the pastebin, i copied it from the same link above.

# Answer
> 1 votes
Here is how to convert the raw triangles into welded vertices, face normals and vertex normals. It is a small code, and it works well:

```
void get_vertices_and_normals_from_triangles(vector<triangle> &t, vector<vertex_3> &fn, vector<vertex_3> &v, vector<vertex_3> &vn)
{
    fn.clear();
    v.clear();
    vn.clear();

    if(0 == t.size())
        return;

    cout << "Triangles: " << t.size() << endl;

    cout << "Welding vertices" << endl;

    // Insert unique vertices into set.
    set<vertex_3> vertex_set;

    for(vector<triangle>::const_iterator i = t.begin(); i != t.end(); i++)
    {
        vertex_set.insert(i->vertex[0]);
        vertex_set.insert(i->vertex[1]);
        vertex_set.insert(i->vertex[2]);
    }

    cout << "Vertices: " << vertex_set.size() << endl;

    cout << "Generating vertex indices" << endl;

    // Add indices to the vertices.
    for(set<vertex_3>::const_iterator i = vertex_set.begin(); i != vertex_set.end(); i++)
    {
        size_t index = v.size();
        v.push_back(*i);
        v[index].index = index;
    }

    vertex_set.clear();

    // Re-insert modifies vertices into set.
    for(vector<vertex_3>::const_iterator i = v.begin(); i != v.end(); i++)
        vertex_set.insert(*i);

    cout << "Assigning vertex indices to triangles" << endl;

    // Find the three vertices for each triangle, by index.
    set<vertex_3>::iterator find_iter;

    for(vector<triangle>::iterator i = t.begin(); i != t.end(); i++)
    {
        find_iter = vertex_set.find(i->vertex[0]);
        i->vertex[0].index = find_iter->index;

        find_iter = vertex_set.find(i->vertex[1]);
        i->vertex[1].index = find_iter->index;

        find_iter = vertex_set.find(i->vertex[2]);
        i->vertex[2].index = find_iter->index;
    }

    vertex_set.clear();

    cout << "Calculating normals" << endl;
    fn.resize(t.size());
    vn.resize(v.size());

    for(size_t i = 0; i < t.size(); i++)
    {
        vertex_3 v0 = t[i].vertex[1] - t[i].vertex[0];
        vertex_3 v1 = t[i].vertex[2] - t[i].vertex[0];
        fn[i] = v0.cross(v1);
        fn[i].normalize();

        vn[t[i].vertex[0].index] = vn[t[i].vertex[0].index] + fn[i];
        vn[t[i].vertex[1].index] = vn[t[i].vertex[1].index] + fn[i];
        vn[t[i].vertex[2].index] = vn[t[i].vertex[2].index] + fn[i];
    }

    for(size_t i = 0; i < vn.size(); i++)
        vn[i].normalize();
}

```

Where the less-than operator is implemented as:

```
inline bool operator<(const vertex_3 &right) const
{
    if(right.x > x)
        return true;
    else if(right.x < x)
        return false;

    if(right.y > y)
        return true;
    else if(right.y < y)
        return false;

    if(right.z > z)
        return true;
    else if(right.z < z)
        return false;

    return false;
}

```

Also, make sure that you sort the vertices before interpolation, if you're using floats instead of doubles. This is because cracks can form in the mesh if the vertices aren't sorted.

```
vertex_3 marching_cubes::vertex_interp(const float isovalue, vertex_3 p1, vertex_3 p2, float valp1, float valp2)
{
    // Sort the vertices so that cracks don't mess up the water-tightness of the mesh.
    // Note: the cracks don't appear if you use doubles instead of floats.
    if (p2 < p1)
    {
        vertex_3 tempv = p2;
        p2 = p1;
        p1 = tempv;

        float tempf = valp2;
        valp2 = valp1;
        valp1 = tempf;
    }

    const float epsilon = 1e-10f;

    if(fabs(isovalue - valp1) < epsilon)
        return(p1);

    if(fabs(isovalue - valp2) < epsilon)
        return(p2);

    if(fabs(valp1 - valp2) < epsilon)
        return(p1);

    float mu = (isovalue - valp1) / (valp2 - valp1);

    return p1 + (p2 - p1)*mu;
}

```

The full codes are at:

https://github.com/sjhalayka/marching\_cubes

https://github.com/sjhalayka/opengl1\_stlview

---
Tags: unity, marching-cubes
---