# Question
Title: How to render top-down perspective in a tile-based RPG?
My question is specifically about the type of perspective that GBA Pokemon games like Fire Red/Leaf Green have:

I'm not sure of the correct terms for what I'm trying to achieve.

I am using SDL2 and can render a tilemap and sprites on top of it, with basic collision detection, but since everything is constrained inside a tile, it looks like the player collides with a wall when their head touches it, rather than the feet.

The above screenshot has a tiny bit of perspective (is that considered 2.5d?), so the head of the player hides a portion of the tile above.

There are definitely ways to make this work, e.g. being a bit more lenient on collision (i.e. not the whole bounding box of the player but the middle of it collides with a wall), but my question is mostly about efficient rendering.

Is rendering from the bottom up the best thing to do so that I respect the perspective? If it is then I guess I need to know at which tile to render the player, so I need to compare every coordinate with the player coordinates to see if it's time to render the player?

# Answer
If you are working with 2D, you usually work with two coordinates for the game logic, so x and y for a position of your objects. Additional, every object has an additional boundary, like a width and a height. If you got deterministic positions, these boundaries are most likely the size of a tile. Like a chess board.

Now, for the graphic steps, you work with the x and y position for your sprites, additional you got the size of your texture (like width and height) and also you got a z-order.

This order is basicly the depth of an texture. So if you want to draw your character above the ground. your ground textures need to have the z-value of 0, your character would have 1.
When your character stands infront of a tree, you should give them both the same z-value, then then draw the obects in the order of their y position, since that means its closer to the camera. The Branch on the this tree would then have an z-value of 2.

What you then do draw your objects in z-order starting with the lowest, so first the ground (value 0), then objects (value 1), then overhanging objects like a branch (value 2).

Every vertice has its own z-value. So for the most part, every vertice for a sprite should have the same z-value. If you dont give a z-value to a vertices, by default the y-position is chosen.
> 1 votes

# Answer
If you can, it's best to do everything in 3D and just render it from a fixed angle. It worked for games that feel completely 2D (Enter the Gungeon) and for games that are 3D (LoZ: A link between worlds, though there the developers had to skew everything a bit to make everything visible).

If you can't use 3D, it's best to use layers and keep track of the player. Link to the past used this approach for instance. The top levels where in a different layer and whenever the player used stairs it would transfer it to a different layer.
> 0 votes

# Answer
You don't need to consider when to render the player. Simply render your whole scene from the top of the screen to the bottom, with transparency around the parts which will overlap the tile above. Controlling render order was the old fashioned way to produce isometric games with tiles overlapping those behind them, and it will work in this way too.

Compared to a 3d-based approach, such as that advocated by Bálint, this approach has the advantage that you have pixel perfect control over your images which is better if you want to have a stylised pixel art look, but means that effects such as lighting and shadow are harder to model accurately.
> 0 votes

---
Tags: rendering, tilemap, sdl2, projection, haskell
---


# Question
Title: how to use vehicles in a sandbox with gamepad
hello I have a game prototype in unity about a local multiplayer sandbox game with gamepad.

The game tries to use vehicles and perform an activity x and I want it to be for 2 people.

At this moment I have a car, a limousine, a tank, a fire truck and an ambulance.

I use Rewired for the input of the gamepad, but the problem I have is that what is already programmed is wrong, that is, everything works in its own scene. In CarScene I have my car and when I move the sticks of the gamepad it moves as it should, so in TankScene my tank moves because it inherits from car and a method of shooting is added, and so on, the ambulance only sounds its siren and the firefighter's cabin shoots water with a shader. But when the players in a scene all move at the same time. Because basically I program in the Update () that takes the movement of the left stick and the movement is applied.

What I need and it is not clear to me is how I can make it possible to select only one vehicle, similar to GTA, a character walks through the city, approaches a vehicle, enters it with a button, at this moment all the Vehicle operations, the player presses a button to exit the vehicle and the control now reprocesses the character.

In fact I already have my modified version of ThirdPersonControl using REWIRED.

The first idea that I have is that in the player's component, a reference to which vehicle is being used is added and it is left null when walking, and add the reference when the button is pressed near a vehicle.

The second idea I had was to create a vehicle-level variable, turn it on and off with the same logic that I require

```
Vehicle {
Update () {
if (IsInUse)
    ProcessInput ()

```

And the last thing that occurred to me was to add a Player object in each vehicle, leave it in null when the vehicle is not in use and activate it

```
Vehicle{ //car inherits from here
Update () {
if (player! = null)
    ProcessInput ()

```

But I feel that with these approaches at some point I am going to have a bug when two vehicles are very close to the command to enter, activate both and cause bad behavior. Or worse, that at some point you lose the reference of which vehicle is active and nothing moves or the character.

I hope you can help me, and that is that I already thought a lot about it in my head, but I feel that I do not have the right solution for the problem

# Answer
> 1 votes
A common approach to the issue of "taking control" is to treat a controller as it's own entity within the game, and have objects with a Possessable script. The idea is the following:

You query input from a Possessable. For example in your car controller

```
public Possessable Possessable;

private void Update() {
  if (!Possessable.Possessed) return;
  if (Possessable.GetButton((int)InputEnum.VehicleAccelerate))
  {
    DriveForward();
  }
}

```

Your Possessable is basically a wrapper around a controller. Your player is also Possessable. To start the game you call

```
Possessable playerPossessable = playerGameObject.GetComponent<Possessable();
playerPossessable.Possess(Rewired.ReInput.players.GetPlayer(mainPlayerID));

```

to pass control to another possessable you can use

```
Possessable vehiclePossesable;
Possessable myPossessable;
myPossessable.PassPossession(vehiclePossesable);

```

Now to show you what this component actually will look like

```
public class Possessable : Monobehaviour
{
  private Rewired.Player currentPlayer = null;

  public bool CanPosses { get { return currentPlayer == null; } }
  public bool Possessed { get { return currentPlayer != null; } }

  public bool Possess(Rewired.Player player) {
    if (!CanPossess) return false;
    currentPlayer = player;
    return true;
  }

  // Convenience if you want to not be possessing anything.
  public Rewired.Player UnPossess() {
    Rewired.Player toRet = currentPlayer;
    currentPlayer = null;
    return toRet;
  }

  public bool PassPossession(Possessable other) {
    if (other.Possess(currentPlayer)) {
      currentPlayer = null;
      return true;
    }
    return false;
  }

  public bool GetButton(int rewiredIndex) {
    if (currentPlayer == null) return false;
    return currentPlayer.GetButton(rewiredIndex);
  }

  // Write similar wrapper functions for the other input methods
}

```

This method has lots of booleans to check to ensure the possession went through. It will ensure only one thing is possessed at a time if you use the PassPossession method. You can in your update loop for a controller, check if you are possessed to avoid needlessly polling input.

In terms of how to choose which vehicle to possess when multiple are close. You should just have a trigger around your player and track whichever possessable objects are currently inside and when the player presses the button, pick 1 from that list. Usually the one closest to you.

---
Tags: unity, gamepad
---


# Question
Title: Does game client size always grow in size after updates?
Games that are updated in course of their lifetime (through online updates), grow in size and I can understand that new textures, sounds and other stuff takes up space. What I'm interested in is - what if an update featured only code cleanup, a lot of old unused features and code were removed.

Does that mean the update would make the game client smaller in size?

I have general programming knowledge, but never had experience with developing game clients.

# Answer
> 1 votes
Yes this is possible. Less code can mean the executable shrinks.

Compiled code is generally pretty compact, so a non-trivial amount of code would need to be removed for the difference to be noticeable.

Refactoring or simplifying code has a tendancy to involve removal and this will cause the executable to shrink a bit. This *can* happen in an update to the game systems. An entire mechanic could be found to be broken and is subsequently removed from the game. Although a lot of game logic is handled by a server, some clients will run a large subset of the same code for prediction purposes, so a removal of that server code would mean a removal of client code as well.

Another more practical possibility is replacing a dependency. For instance, someone might use one or more parts of the boost library at first but later find a better replacement for the features they were using. Another example would be switching serialization libraries for performance reasons, but the new one they choose *happens* to have a smaller binary size.

# Answer
> 0 votes
There is code in the client to handle actions that the player performs and code for displaying the world (among other things). If those change, the client size will change (either grow or shrink depending on behavior added/removed).
Much of the game code is on the server however, and doesn't directly affect client.

Unless new game mechanics are implemented that either affect how the game plays or the world renders, I imagine most games' client code stays the same between updates

---
Tags: architecture, client
---


# Question
Title: How to get the tangent and normal of a collision?
In my game, one of my objects casts a ray into a 2d space. If that ray were to hit another object, I'd like to draw a line that is perpendicular to the tangent of the ray's hit point. So when the ray hits the other object, a tangent is formed at the point of contact, and then I'd like to use the linerenderer component to draw a line that is perpendicular to that tangent. I already know how to use the linerenderer to draw lines, but I don't know how to get the tangent and normal from a collision.

```
  if (Input.GetMouseButton(0))
    {
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        var direction = (mousePos - (Vector2)cueBall.position).normalized;

        var hit = Physics2D.Raycast(cueBall.position, direction, Mathf.Infinity, 1 << LayerMask.NameToLayer("Ball"));

        if (hit)
        {
            _line1.SetPositions(cueBall.position, hit.point); //This is the line from the cueball to the red ball.
            _line2.SetPositions(hit.point, hit.normal); //This is supposed to be the predicted trajectory of the red ball.
        }
    }

```

# Answer
Your vector math here is not correct, nor even meaningful.

```
_line2.SetPositions(hit.point, hit.normal);

```

Here you're using a normal, which is a direction, as though it was a point in space. This does not make geometric sense.

If you want to draw a line from the hit point to a new point *in the direction of* the collision normal *from that hit point* then you'd do it like this:

```
float drawnLength = 1.0f;

var endpoint = hit.point + drawnLength * hit.normal;
_line2.SetPositions(hit.point, endpoint);

```

But this still does not give you the expected trajectory of an elastic collision. It gives you the line of symmetry between the incoming and outgoing trajectories.

To get an estimated bounce trajectory, you need to perform the reflection:

```
var reflectedDirection = Vector2.Reflect(direction, hit.normal);

endpoint = hit.point + drawnLength * reflectedDirection;
_line3.SetPositions(hit.point, endpoint);

```

Also note that for better accuracy in the presence of corners/obstacles, you'll want to use a CircleCast, not a Raycast, to account for the radius of the ball.
> 1 votes

---
Tags: unity, mathematics
---


# Question
Title: Is Rigidbody needed and what move function to use in 2D games?
I don't really fully understand how to use rigidbody and which movement functions in a 2D game. There seems to be so many options and it's just a mess in my head right now. If I'm making a game like those classic 2D zelda games, do I need rigidbody at all? I don't think I will need any physics but I obviously need to check if two objects have collided so I can do some logic on them, like destroying an object on collision or hurt the player, or stop movement if player walks into a wall.

Is going with no Rigidbody and moving only with transform.translate a good choice with these types of games?

# Answer
Rigidbodies are required when you want the engine to handle collision detection for you. If you want to prevent your character from walking through other objects with colliders (like walls), then you either have to check for walls in your own movement code or you need to add a rigidbody to your player.

And if you want to use trigger areas which do something when the player walks into them, then that's another reason to add a rigidbody to the player, because that's a requirement for causing OnTriggerEnter events. For more information about the Unity collision rules, check the tables under "Collision action matrix" in the manual article about colliders.

Now about how to move your rigidbody. I created a little demo game which demonstrates the effects of different ways to move a player-character. You can check it out on itch.io.

When an object has a non-kinematic rigidbody, then you should generally not manipulate the transform directly. When you change the transform, you are not *moving* the object, you are *teleporting* the object. This ignores collision and can cause weird effects if you teleport an object into another object with a rigidbody.

If you want physics in your game (objects pushing each other and getting pushed in a physically correct way), then the cleanest and most recommendable way is to control objects with Rigidbody.AddForce. When you feel like your objects behave too much like they are gliding on ice that way, increase the drag value of your rigidbodies. The result will be that your objects move with a bit of momentum, which often looks and feels pretty nice.

If you are looking for something in between the physically correct movement of handling forces and the tight control of manipulating the transform, manipulate the velocity property of the rigidbody. That way you still have collision handling and can push things, but the object itself won't behave in a physically corret way when interacting with other objects.
> 1 votes

---
Tags: unity, 2d, collision-detection, physics, rigidbody
---


# Question
Title: Why does my sprite shifts position on specific animationframe?
I have created a spritesheet to create animation. Everything is working fine untill I come to a specific frame in one animation.

I have currently 3 animations loops

1. Idle Animation
2. Moving Animation
3. Shooting Animation

Nr 1,2 is working fine and behave like they should but when I am shooting my sprite shifts a little to the left. And I don't why it does.

Here is a gif for the animations

Here is the spritesheet I am using for the animations

And here is the code I am using for looping and shifting different animations

```
public void DrawSpriteSheetFrame(CustomTexture2D ct, Vector2 position, StateOfObject soo, GameTime gt, SpriteFont sf)
    {
        if (!_currentstate.Equals(soo))
        {
            _currentframe = 0;
        }
        _currentstate = soo;

        List<SpriteFrameInfo> currentLoopsheet = ct.SubTexture.FindAll(x => x.name.Contains(soo.ToString()));
        _timeSinceLastFrame += gt.ElapsedGameTime.Milliseconds;
        if (_timeSinceLastFrame > _frameUpdateSpeed)
        {
            _timeSinceLastFrame -= _frameUpdateSpeed;
            if (_currentframe <= currentLoopsheet.Count - 1)
            {
                _currentframe++;
            }
            else _currentframe = 0;
        }
        var t = currentLoopsheet.Where(x => x.name.Contains(_currentframe.ToString())).FirstOrDefault();
        Vector2 origin = new Vector2(t.width, t.height);
        var rec = new Rectangle(0,0, 400,200);
        _spriteBatch.Begin();
        _spriteBatch.DrawString(sf, "Currentsheet: " + t.name, new Vector2(100), Color.White);
        _spriteBatch.DrawString(sf, "Position X: " + position.X, new Vector2(100,150), Color.White);
        _spriteBatch.DrawString(sf, "Position Y: " + position.Y, new Vector2(100,200), Color.White);
        _spriteBatch.DrawString(sf, "SheetCord X: " + t.x, new Vector2(100, 250), Color.White);
        _spriteBatch.DrawString(sf, "SheetCord Y: " + t.y, new Vector2(100, 300), Color.White);
        _spriteBatch.Draw(ct.Texture, position, new Rectangle(new Point(t.x, t.y), new Point(t.width, t.height)), Color.White, 0, origin, 1, SpriteEffects.None, 1);
        //DrawBorder(new Rectangle(new Point(t.x, t.y), new Point(t.width, t.height)), 1, Color.Black);
        //_spriteBatch.Draw(ct.Texture, position, new Rectangle(new Point(t.x, t.y), new Point(t.width, t.height)), Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);
        //_spriteBatch.Draw(ct.Texture, position, rec, Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 1);

        _spriteBatch.End();
    }

```

# Answer
> 1 votes
I think one frame of the shooting animation has a different width than the rest of the frames, which seems noticeable when looking at the sprite sheet.

EDIT: Looking at it again, I think this has to do with the `sheetCord`, which translates to me to "Spritesheet Coördination". So the coder who made this uses a spritesheet as the whole image, and uses specific positions for every frame of the spritesheet to show the right image out of it.

It appears that one position is misarranged, likely edited by someone else. so if you're able to find the location where all spritesheet positions are located, you can also change the value of the position of the misplaced frame to correct it again.

Hope this helps.

---
Tags: animation, sprites, monogame, spritesheet
---


# Question
Title: How can I create a pixellated, limited-palette appearance in modern OpenGL?
I wanna get some old art style (256 color, dithering, etc) in modern OpenGL in an effective way. Maybe using a low resolution (320x240) rendered at a bigger space so that the pixels looks "bigger?" I'd just like to fake this old style on modern GPUs.

# Answer
To get pixelated look, you can use OpenGL's framebuffer functionality to render to texture (glFramebufferTexture2D etc.), then draw that texture as a rectangle with nearest-neighbour scaling.
> 1 votes

---
Tags: opengl, c++
---


# Question
Title: Background music not stopping while game is set to paused
I am implementing pause game functionality in a Unity3D game using the following script

```
    public class PauseGame : MonoBehaviour
    {
        /// <summary>
        /// class to pause the game using Time.timeScale and
        /// implement the related behaviours associated the game
        /// </summary>

        #region Fields

        // Boolean variable that informs script if game should be paused or not, false by default.
        private bool isPaused = false;

        #endregion

        #region MonoBehaviour Messages

        /* ----------------------------------------
         * At Start,
         *
         */
        void Start()
        {

        }

        /* ----------------------------------------
         * Whenever 'ESC' key is pressed, toggle 'isPaused' boolean
         * and call SetPause() to pause/resume game
         */
        void Update()
        {
            if (Input.GetKeyDown(KeyCode.Escape))
            {
                isPaused = !isPaused;
                SetPause();
            }

        }

        #endregion

        #region Methods

        /* ----------------------------------------
         * A function to pause/resume the game
        */
        public void SetPause()
        {
            Debug.Log("SetPause");

            // Invert 'isPaused' boolean and convert it into a float variable, being true = 1; and false = 0f.
            float timeScale = !isPaused ? 1f : 0f;

            // Set the Time Scale as 1(game runs normally) or 0(game pauses)
            Time.timeScale = timeScale;

        }
        #endregion
    }

```

All the game elements pause as expected using the above, except the background music. I can pause the background music by additionally referencing the AudioSource and disabling it while timescale is set to 0. However, I was wondering whether it was a bug. Kindly suggest.

# Answer
This isn't a bug. AudioSource will play independent of timescale. So you will need to reference your AudioSource and call .Pause() in your pause class.
> 1 votes

# Answer
You can use AudioListener.pause to true to pause them. and also you can specify some sounds sources to ignore that by setting AudioSource.ignoreListenerPause to true. Useful when you want some separate sounds to work while in pause menu.
> 0 votes

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


# Question
Title: Open world loading/unloading with asset bundle in unity
I have a very large environment which I have to load/unload in unity Webgl as I can't load them at once. So, I have divide the environment into 1000 x 1000m (1km) (each chunk is consist of three layer like objects layer, tree layer,floor layer) chunks and on my player I have attached this script for chunk loading/unloading, thanks to this guide.

```
    public class TileLoadingManager : MonoBehaviour
    {
        //[SerializeField]
        public string tileTag;

        //[SerializeField]
        public Vector3 tileSize;

        //[SerializeField]
        public int maxDistance;

        public GameObject[] tiles;

        // Use this for initialization
        void Start()
        {
            this.tiles = GameObject.FindGameObjectsWithTag(tileTag);
            DeactivateDistantTiles();
        }

        void DeactivateDistantTiles()
        {
            Vector3 playerPosition = this.gameObject.transform.position;

            foreach (GameObject tile in tiles)
            {
                Vector3 tilePosition = tile.gameObject.transform.position + (tileSize / 2f);

                float xDistance = Mathf.Abs(tilePosition.x - playerPosition.x);
                float zDistance = Mathf.Abs(tilePosition.z - playerPosition.z);

                if (xDistance + zDistance > maxDistance)
                {
                    tile.SetActive(false);
tile.GetComponent<PerRegionABCaller>().AbLoadCall();

                }
                else
                {
                    tile.SetActive(true);
 tile.GetComponent<PerRegionABCaller>().AbUnLoadCall();
                }
            }
        }

        void Update()
        {
            DeactivateDistantTiles();

        }
    }

```

Its loading/unloading my chunks but a problem is that, it is a costly method for load/unload as my object chunk (tile) count is around 4 (expected to grow). Additionally I am loading asset bundle from `UnityWebReqest` and destroying assets on-unload, so it very heavy task. So my question is that is this the right approach or I should need to adopt anything else?

**EDIT:** Bundle Loading Code Snippet:

```
public void AbLoadCall()
    {
        if (AbLoadCallCortoutineRef == null)
        {
            AbLoadCallCortoutineRef = StartCoroutine(AbLoadCallCoroutine());
        }
    }

    IEnumerator AbLoadCallCoroutine()
    {
        for (int i = 0; i < perRegionAssetBundleList.Length; i++)
        {
            yield return StartCoroutine(perRegionAssetBundleList[i].DownloadABCall());
        }

    }

```

Actual Loading Code:

```
    public IEnumerator DownloadABCall()
    {
        if (!abObjectInstantiated)
        {
            //Debug.Log(assetName + " , downloading assetbundle. . ");
            yield return StartCoroutine(DownloadAB(assetBundleURL));
        }
        else
        {
            //Debug.Log("Reactivintg");
            if (!abObjectInstantiated.activeInHierarchy)
            {
                //Debug.Log("Reactive done"+ this.assetName);
                abObjectInstantiated.SetActive(true);
            }

            if (floorL7MeshRenderer)
            {
                floorL7MeshRenderer.enabled = false;
            }

        }
        //else
        //{
        //    Debug.Log(this.name + " , Bundle object has alread available.");
        //}
    }

 IEnumerator DownloadAB(string bundleURL, string assetName = "")
    {
        Debug.Log(". . DownloadAB. . ,"+ this.name);
        isBundleLoading = true;

        www = UnityWebRequestAssetBundle.GetAssetBundle(bundleURL);
        //Debug.Log("web req about to send : " + assetName);

        yield return www.SendWebRequest();

        if (www.error != null)
        {
            Debug.LogError("assetBundleURL : " + assetBundleURL);
            Debug.LogError("www error : " + www.error);
            www.Dispose();
            www = null;
            yield break;
        }

        //Debug.Log("bundle loading , "+ assetName);

        // get bundle from downloadhandler
        AssetBundle bundle = ((DownloadHandlerAssetBundle)www.downloadHandler).assetBundle;

        GameObject bundlePrefab = null;

        bundlePrefab = (GameObject)bundle.LoadAsset(bundle.GetAllAssetNames()[0]);

        // if we got something out
        if (bundlePrefab != null)
        {

            abObjectInstantiated = (GameObject)Instantiate(bundlePrefab);
            abObjectInstantiated.transform.parent = envParent.transform;

            if (floorL7MeshRenderer)
            {
                floorL7MeshRenderer.enabled = false;
            }

        }

        www.Dispose();
        www = null;

        Resources.UnloadUnusedAssets();
        bundle.Unload(false);
        bundle = null;

        isBundleLoading = false;
        //Debug.Log("bundle unloading completed ," + assetName);
    }

```

# Answer
I am assuming you are loading `AssetBundle` at Start. If so then your method `DeactivateDistantTiles()` is too expensive to be called in `Update()` since its been called every frame and your `Coroutines` are nested and in a `for loop` and telling Update method to delay which is wrong until and unless it is being validated properly. So you need to change your code structure a little bit.

If you are loading multiple assets so make sure to make a list and add your items to that list. When you are done downloading assets use that list in your game. For example:

```
List<GameObject> listOfGameObjects = new List<GameObject>();

```

In your case:

```
if (bundlePrefab != null)
{
    listOfGameObjects.Add(bundlePrefab);
}

```

Then in Update you can do something like this: (You can modify according to your need)

```
public void Update()
{
    if(HasDownloadFinished)
    {
        foreach (var bundle in listOfGameObjects)
        {
            abObjectInstantiated = (GameObject)Instantiate(bundle);
            abObjectInstantiated.transform.parent = envParent.transform;

            if (floorL7MeshRenderer)
            {
                floorL7MeshRenderer.enabled = false;
            }
        }
    }
    else if(isDownloading)
    {
        //Restrict player to go beyond your Game View screen.
        //Start downloading chunks again here
    }

}

```

Also try to use `CachedAssetBundle`. Its useful when you download assets frequently. According to Unity's docs

> The caching system keeps track of the last version number passed to UnityWebRequest. When this API is called with a version number, the caching system checks to see if there is a cached AssetBundle by comparing version numbers. If these numbers match, the system will load the cached AssetBundle. If the numbers do not match, or there is no cached AssetBundle, then Unity will download a new copy. This new copy will be associated with the new version number.

For more information about built-in caching AssetBundle, click here.
> 2 votes

# Answer
I would suggest that you sort these chunks into a lookup table, either a 2D array `GameObject[,]` or a `Dictionary<int2, GameObject>`. For each of your chunks you would then store it in your lookup on the index `int2(floor(x / tileSize), floor(z / tileSize))`.

When iterating your chunks you only have to go over a certain number of indices, rather than going over the whole list of chunks. In pseudo code this could look like:

```
int maxDist = ceil(maxDistance / tileSize);
int2 myPos = new int2(floor(me.x / tileSize), floor(me.z / tileSize));
for (int y = myPos.y - maxDist; y < myPos.y + maxDist; y++)
  for (int x = myPos.z - maxDist; z < myPos.z + maxDist; z++)
    if (chunkLookup.TryGetValue(new int2(x, y), out var chunk)
      if (!chunk.active)
        activate(chunk);
        activeList.Add(chunk);

```

By storing all active chunks in a list, you can easily iterate over the active chunks, to see which ones to unload, and remove from the active list.

Edit: You might need to enable Unity.Mathematics in the Package Manager, in order to use int2.
> 1 votes

# Answer
The simplest thing I can think of right now would be to change it into much smaller chunks (something like Minecraft's 16x16 chunks) but maybe more like 64x64. If any chunks are within, say, 256 units of the player, then they will be loaded. Once they go outside of that, they would be unloaded, and any new chunks would be then loaded.

I am sorry, but I cannot think of any code for it as my computer with unity on it is currently being repaired.

But that should not be too hard to implement.
> 0 votes

---
Tags: unity, webgl, loading, open-world, assetbundle
---


# Question
Title: (Unity) Values set in Start() will be reset?
This is my `GameController` GameObject in the Inspector (Ignore `Suns` and `Player`). Note that the `GameController` script has `GameSpawner` as a `SerializeField`.

And my script for GameController below.

```
public class GameController : MonoBehaviour
{
    public GameObject sunParent;
    public GameObject playerPrefab;

    [SerializeField]
    GameObject sunSpawnerObject;

    SunSpawner sunSpawner;

    void Start()
    {
        sunSpawner = sunSpawnerObject.GetComponent<SunSpawner>();
    }

    // this is only for testing
    void LateUpdate()
    {
        SpawnSunAtY(sunParent, -3.5f);
        SpawnSunAtY(sunParent, 0f);
        SpawnSunAtY(sunParent, 3.5f);
    }

    void SpawnSunAtY(GameObject parent, float y)
    {
        sunSpawner.SpawnSunAtY(parent, y);
    }

}

```

When the Scene starts, it should get the `SunSpawner` script from `sunSpawnerObject`. Then what is `SunSpawner`? See below.

This GameObject(prefab) has `SunSpawner` script as a component. And below the script for `SunSpawner`. (*where my question begins*)

```
public class SunSpawner : MonoBehaviour
{
    const float SUN_MIN_SIZE_FACTOR = 0.05f;
    const float SUN_MAX_SIZE_FACTOR = 0.3f;

    [SerializeField]
    GameObject sunPrefab;

    float playerRawRadius;
    float sunRawRadius;

    void Start()
    {
        // these lines work just fine
        GameObject player = GameObject.FindGameObjectWithTag("Player");
        playerRawRadius = player.GetComponent<Renderer>().bounds.size.x / 2f;
        sunRawRadius = sunPrefab.GetComponent<Renderer>().bounds.size.x / 2f;
    }

    public void SpawnSunAtY(GameObject parent, float y)
    {
        float sizeFactor = Random.Range(SUN_MIN_SIZE_FACTOR, SUN_MAX_SIZE_FACTOR);

        Vector3 position = new Vector3(GetRandomXPos(sizeFactor), y, 0);
        GameObject sun = Instantiate(sunPrefab, position, Quaternion.identity);
        sun.transform.localScale *= sizeFactor;
        sun.transform.parent = parent.transform;
    }

    float GetRandomXPos(float sizeFactor)
    {
        float offset = Camera.main.WorldToScreenPoint(new Vector3(GetHorizontalOffsetFromScreen(sizeFactor), 0, 0)).x;
        float screenRightBoundWorldPoint = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0, 0)).x;
        float screenLeftBoundWorldPoint = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 0)).x;

        return Camera.main.ScreenToWorldPoint(new Vector2(Random.Range(offset, screenRightBoundWorldPoint - offset), 0)).x;
    }

    float GetHorizontalOffsetFromScreen(float sizeFactor)
    {
        float horizontalMargin = 0.1f; //TODO temporary value
        float playerRadius = playerRawRadius;  // *look here (1)*
        float distancePlayerToSun = 0.5f; //TODO temporary value
        float randomRadius = GetRandomRadius(sizeFactor);

        return horizontalMargin + (2f * playerRadius) + distancePlayerToSun + randomRadius;
    }

    float GetRandomRadius(float sizeFactor)
    {
        // *look here (2)*
        print("sunRawRadius: " + sunRawRadius + ", sizeFactor: " + sizeFactor + ", scaledRadius: " + (sunRawRadius * sizeFactor));
        return sunRawRadius * sizeFactor;
    }
}
```

Call stack:

`GameController.LateUpdate()` -\> `SunSpawner.SpawnSunAtY(parent, y)` -\> `SunSpawner.GetRandomXPos(sizeFactor)` -\> `GetRandomXPos(sizeFactor)` -\> `GetHorizontalOffsetFromScreen(float sizeFactor)` -\> `GetRandomRadius(sizeFactor)`

Look here (1):

in `SunSpawner.Start()`, all values are initialized properly, I can see values in the debugger or log. However, when I get to `GetHorizontalOffsetFromScreen(..)`, I see `playerRawRadius` is now zero.

Look here (2):

Same thing. `sunRawRadius` is 0, but `sizeFactor` argument is properly passed down the call stack.

**Question: Why is it doing this?**

**Follow up: How do I properly instantiate prefabs through game object chains and use them?**

Big thank you in advance.

# Answer
> 2 votes
Like a lot of problems I think this stems from a misunderstanding of prefabs and a slight design issue. What you're looking to do is essentially make a manager type class, that is spawning and managing instances of suns. If this sun spawner is only in one scene, then you should simply have an instance of that prefab in your scene and link it from that instance. Prefabs not in a scene are just templates. They don't actually run or execute. If you need your sun spawner across multiple scenes then I will demonstrate a good setup for that.

Let's start with a unity Singleton pattern. This pattern is useful for global systems that have exactly one instance. While in other coding environments singletons are often frowned upon, they tend to make a lot of sense in game environments. Just don't go overboard.

```
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
  public static T Instance { get; private set; }

  // Checks if we already have an instance, if so
  // We don't need this gameObject
  protected virtual void Awake() {
    if (instance != null) {
      Destroy(gameObject);
      return;
    }
    Instance = this
  }

  protected virtual void OnDestroy() {
    if (Instance == this) Instance = null;
  }
}

```

Expanding on this we have a singleton that will persist across multiple scenes if we want

```
public class PersistentSingleton<T> : Singleton<T>
{
  protected override void Awake() {
    base.Awake();
    DontDestroyOnLoad(gameObject);
  }
}

```

Finally let's make a prefab with the following script on the root

```
// An empty persistent singleton which will ensure only one instance
// of itself is ever created, and it will persist across scene changes
public class PersistentEntities : PersistentSingleton<PersistentEntities>
{
}

```

We'll call that prefab we made PersistentEntities, and within it you can put all your systems you wish to persist across multiple scenes. In each and every scene you should place an instance of this prefab. Since it persists across scenes, when it loads to another scene, the PersistentEntities instance in the new scene will see that an instance already exists via the Singleton pattern, and destroy itself. Now you have the tools to do with as you wish. If your SunSpawner is only in one scene, or only a few scenes, then maybe you should just make a SunSpawner prefab with a SunSpawner script that inherits from Singleton. If you need the sunspawner in multiple consecutive scenes and it should maintain it's state across scenes, then you could put SunSpawner inside your PersistentEntities prefab.

Hopefully these tools can help you resolve your issues. But you should decide what your SunSpawner is. Does it need to maintain information across scenes? Put it in PersistentEntitites and make it Singleton. Is it a system that should only have one instance, but it's information doesn't need to be across scene? Make it Singleton, then put an instance in the scenes you need it. Do scenes have multiple SunSpawners? Then don't make it either, and you can put multiple instances in your scene, or Instantiate them from a prefab before using them.

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


# Question
Title: Making the camera look at the player while keeping another object in view
I'm working on a sorta football game where I need my player to always be at the center of the camera view while keeping the ball into view, without any vertical movement. The idea would be for the camera to act like the picture below.

What I came up with was the following code that I'm using in a LateUpdate. I'm computing a directional vector between the player and the ball and placing my camera behind the player using that data, and then I look at my player.

```
Vector3 ballPosition = ballTransform.position;
Vector3 playerPosition = playerTransform.position;

ballPosition.y = 0.0f;
playerPosition.y = 0.0f;

Vector3 directionVector = (ballPosition - playerPosition).normalized;
directionVector.y = 0.0f;

Vector3 newPosition = playerTransform.position - directionVector * 12.0f;
newPosition.y = 9.0f;

transform.position = newPosition;

transform.LookAt(playerTransform.position);

```

The code itself is working, but the camera movement is a bit nauseous, and when I'm trying to smooth it I end up with the ball leaving the camera field most of the time. Plus when I get too close from the ball I end up with some really quick camera movements which makes the whole thing kinda hard to follow. I tried to use a totally different technique by working with a Cinemachine Camera, but there doesn't seem to be an easy way to achieve such a view.

Does anyone have an idea of how to achieve such a thing?

# Answer
This is less of a technical problem and more of a design problem. You've got the technical part right, now it's just playing with values. One solution could be to use the SmoothDamp function for the position of your camera

```
private Vector3 vel = Vector3.zero

LateUpdate() {
  float dampTime = 3;
  transform.position = SmoothDamp(transform.position, newPosition, ref vel, dampTime);
}

```

If you want to keep the ball in focus at all times, (which i'd advise having some leeway as you'll never be able to achieve this and have perfectly smooth camera all the time. Even fifa let's the ball go offscreen in edge cases) then you could change dampTime by a function of the ball's screen coordinates. If the ball is at the edge of the screen, follow faster, if it's close to the center we can follow slower. This value however is tricky to discern because ideally you'd want the camera to rotate at pace to keep the ball on screen. So maybe you'd want a function that takes the ball's 3D position and velocity relative to the camera frustum? Like I said this is definitely a design question, but SmoothDamp will make your life easier.
> 1 votes

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


# Question
Title: How can I change a sprite used for a Unity Tilemap tile at runtime?
I want to change Tile's sprite during runtime, but it doesn't render.

```
class SwitchableTile : Tile
{
  // usable sprites
  public Sprite[] sprites;
  // index to the sprite
  private int spriteIndex = 0;

  // I don't know when it's called
  // but set sprite to current spriteIndex
  public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
  {
      // ..
      if (sprites != null && sprites.Length > 0)
      {
        tileData.sprite = sprites[spriteIndex];
      }
   }
  // called per Tilemap.RefreshTile
  public override void RefreshTile(Vector3Int position, ITilemap tilemap)
  {
    tilemap.RefreshTile(position);
  }
}

```

Also tried to refresh the tile according to the position:

```
// in MonoBehaviour
BoundsInt bounds = tilemap.cellBounds;
bool updated = false;

foreach (Vector3Int pos in bounds.allPositionsWithin)
{
  TileBase tile = tilemap.GetTile(pos);
  if (tile && tile is SwitchableTile)
  {
    if (!updated)
    {
      // just loop index
      Sprite sprite = ((SwitchableTile)tile).GetNextSprite();
      // set sprite
      ((SwitchableTile)tile).sprite = sprite;

      updated = true;
    }
    // refresh
    tilemap.RefreshTile(pos);
  }
}

```

Since `Tilemap.RefreshTile` calls `TileBase.RefreshTile` per refresh, the problem's solved after I implemented `TileBase.RefreshTile`.

I'm not using 2d-extra's animation tile because I want to change sprites only under certain condition. Also not using Tilemap.SwapTile because in this case I'm solving it using customized Tile, instead of creating a new Tile.

---

**Update:** Well...It proves that I need to implement `RefreshTile` for a Tile. Now the sprite refreshes. But I'm still not sure about `GetTileData`, do I need to implement it? When it is called?

# Answer
There are 2 ways to **change a tile's sprite** during runtime:

1. Change tiles in a tilemap to a new tile (SetTiles or SwapTile)
2. Change tile's sprite

Both solution requires **re-rendering** of tiles.

This is why simply setting `tile.sprite` to a new sprite is not enough. I'll explain it later.

---

Tile is only a reference to some attributes. Tiles implement some interfaces to be called in Tilemap, which the latter one stores a grid of information and renders them.

This is important because if you want to customize your tiles, you **do not call them directly** on `CustomizedTile : Tile` like MonoBehaviour classes. You need to implement the interfaces which is used by Tilemap, and call Tilemap's methods.

So, there are two important interfaces: **GetTileData** and **RefreshTile**.

As mentioned in docs, `GetTileData` sets all necessary data for rendering a tile. But the render process is also controlled by `RefreshTile`. It's a bit weird that `TileBase` doesn't implement them by itself, so you have to implement them in your own customized Tile. It's also a bit weird they are not `interface` \- like Unity UI's callbacks.

But here finally comes the solution:

```
// Set sprite for rendering
public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
{
  if (sprites != null && sprites.Length > 0)
  {
    tileData.sprite = sprites[spriteIndex];
  }
}

// Refresh yourself
public override void RefreshTile(Vector3Int position, ITilemap tilemap)
{
  tilemap.RefreshTile(position);
}

```

Now you can change the sprite outside Tile and Tilemap and refresh them (as the question's code snippet provided).

Note the first two options (SetTiles and SwapTile) by Unity automatically calls refresh so you don't have to manually do this.
> 4 votes

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


# Question
Title: How to add state to the custom inspector in Unity
I'm writing a custom inspector for my asset (by deriving from `Editor`), and I have a few variables controlling the state of the inspector (like whether a foldout is opened or not), that I'd like to be saved. I don't want to put them on the object, since then it would end up as junk inside the game state, but I also don't want it to be reset every time I click away from the object and then click back.

Do you guys have an idea where could I put the data so it gets persisted?

# Answer
> 0 votes
I'd recommend putting this type of state information inside an `#if UNITY_EDITOR` conditional compilation block inside the type you're editing. That way it's stored in memory only in the editor, and stripped out of the built game executable by the preprocessor.

It stays associated with the object you were editing, and can be serialized to persist between editing sessions.

---
Tags: unity
---


# Question
Title: How do you generate tileable Perlin noise?
Related:

I'd like to generate tileable Perlin noise. I'm working from Paul Bourke's `PerlinNoise*()` functions, which are like this:

```
// alpha is the "division factor" (how much to damp subsequent octaves with (usually 2))
// beta is the factor that multiplies your "jump" into the noise (usually 2)
// n is the number of "octaves" to add in
double PerlinNoise2D(double x,double y,double alpha,double beta,int n)
{
   int i;
   double val,sum = 0;
   double p[2],scale = 1;

   p[0] = x;
   p[1] = y;
   for (i=0;i<n;i++) {
      val = noise2(p);
      sum += val / scale;
      scale *= alpha;
      p[0] *= beta;
      p[1] *= beta;
   }
   return(sum);
}

```

Using code like:

```
real val = PerlinNoise2D( x,y, 2, 2, 12 ) ; // test

return val*val*skyColor + 2*val*(1-val)*gray + (1-val)*(1-val)*cloudColor ;

```

Gives sky like

Which isn't tileable.

The pixel values are 0-\>256 (width and height), and pixel (0,0) uses (x,y)=(0,0) and pixel (256,256) uses (x,y)=(1,1)

How can I make it tileable?

# Answer
There's two parts to making seamlessly tileable fBm noise like this. First, you need to make the Perlin noise function itself tileable. Here's some Python code for a simple Perlin noise function that works with any period up to 256 (you can trivially extend it as much as you like by modifying the first section):

```
import random
import math
from PIL import Image

perm = range(256)
random.shuffle(perm)
perm += perm
dirs = [(math.cos(a * 2.0 * math.pi / 256),
         math.sin(a * 2.0 * math.pi / 256))
         for a in range(256)]

def noise(x, y, per):
    def surflet(gridX, gridY):
        distX, distY = abs(x-gridX), abs(y-gridY)
        polyX = 1 - 6*distX**5 + 15*distX**4 - 10*distX**3
        polyY = 1 - 6*distY**5 + 15*distY**4 - 10*distY**3
        hashed = perm[perm[int(gridX)%per] + int(gridY)%per]
        grad = (x-gridX)*dirs[hashed][0] + (y-gridY)*dirs[hashed][1]
        return polyX * polyY * grad
    intX, intY = int(x), int(y)
    return (surflet(intX+0, intY+0) + surflet(intX+1, intY+0) +
            surflet(intX+0, intY+1) + surflet(intX+1, intY+1))

```

Perlin noise is generated from a summation of little "surflets" which are the product of a randomly oriented gradient and a separable polynomial falloff function. This gives a positive region (yellow) and negative region (blue)

The surflets have a 2x2 extent and are centered on the integer lattice points, so the value of Perlin noise at each point in space is produced by summing the surflets at the corners of the cell that it occupies.

If you make the gradient directions wrap with some period, the noise itself will then wrap seamlessly with the same period. This is why the code above takes the lattice coordinate modulo the period before hashing it through the permutation table.

The other step, is that when summing the octaves you will want to scale the period with the frequency of the octave. Essentially, you will want each octave to tile the entire just image once, rather than multiple times:

```
def fBm(x, y, per, octs):
    val = 0
    for o in range(octs):
        val += 0.5**o * noise(x*2**o, y*2**o, per*2**o)
    return val

```

Put that together and you get something like this:

```
size, freq, octs, data = 128, 1/32.0, 5, []
for y in range(size):
    for x in range(size):
        data.append(fBm(x*freq, y*freq, int(size*freq), octs))
im = Image.new("L", (size, size))
im.putdata(data, 128, 128)
im.save("noise.png")

```

As you can see, this does indeed tile seamlessly:

With some small tweaking and color mapping, here's a cloud image tiled 2x2:

Hope this helps!
> 100 votes

# Answer
Here's one rather clever way that uses 4D Perlin noise.

Basically, map the X coordinate of your pixel to a 2D circle, and the Y coordinate of your pixel to a second 2D circle, and place those two circles orthogonal to each other in 4D space. The resulting texture is tileable, has no obvious distortion, and doesn't repeat in the way that a mirrored texture would.

Copy-pasting code from the article:

```
for x=0,bufferwidth-1,1 do
    for y=0,bufferheight-1,1 do
        local s=x/bufferwidth
        local t=y/bufferheight
        local dx=x2-x1
        local dy=y2-y1

        local nx=x1+cos(s*2*pi)*dx/(2*pi)
        local ny=y1+cos(t*2*pi)*dy/(2*pi)
        local nz=x1+sin(s*2*pi)*dx/(2*pi)
        local nw=y1+sin(t*2*pi)*dy/(2*pi)

        buffer:set(x,y,Noise4D(nx,ny,nz,nw))
    end
end

```
> 100 votes

# Answer
Ok, I got it. The answer is to walk in a torus in 3D noise, generating a 2D texture out of it.

Code:

```
Color Sky( double x, double y, double z )
{
  // Calling PerlinNoise3( x,y,z ),
  // x, y, z _Must be_ between 0 and 1
  // for this to tile correctly
  double c=4, a=1; // torus parameters (controlling size)
  double xt = (c+a*cos(2*PI*y))*cos(2*PI*x);
  double yt = (c+a*cos(2*PI*y))*sin(2*PI*x);
  double zt = a*sin(2*PI*y);
  double val = PerlinNoise3D( xt,yt,zt, 1.5, 2, 12 ) ; // torus

  return val*val*cloudWhite + 2*val*(1-val)*gray + (1-val)*(1-val)*skyBlue ;
}

```

Results:

Once:

And tiled:
> 26 votes

# Answer
One simple way I can think of would be to take the output of the noise function and mirror/flip it into an image that's twice the size. It's difficult to explain so here's an image:

Now, in this case, it's pretty obvious what you did when you look at this. I can think of two ways to (possibly :-) ) resolve this:

1. You could take that larger image and then generate some more noise on top of it but (and I'm not sure if this is possible) focused towards the middle (so the edges stay the same). It could add the extra bit of difference that would make your brain think it's not just mirror images.
2. (I'm also not sure if this is possible) You could try fiddling with the inputs to the noise function to generate the initial image differently. You'd have to do this by trial and error, but look for features that draw your eye when you tile/mirror it and then try and get it not to generate those.

Hope this helps.
> 16 votes

# Answer
**First version of this answer was actually wrong, I've updated it**

A method I used successfully is make noise *domain* tiled. In other words, make your base `noise2()` function periodical. If `noise2()` is periodic and `beta` is integer, resulting noise will have the same period as `noise2()`.

How can we make `noise2()` periodic? In most implementations, this function uses some kind of lattice noise. That is, it gets random numbers at integer coordinates, and interpolates them. For example:

```
function InterpolatedNoise_1D(float x)

  integer_X    = int(x)
  fractional_X = x - integer_X

  v1 = SmoothedNoise1(integer_X)
  v2 = SmoothedNoise1(integer_X + 1)

  return Interpolate(v1 , v2 , fractional_X)

end function

```

This function can be trivially modified to become periodic with integer period. Simply add one line:

```
integer_X = integer_X % Period

```

before calculating `v1` and `v2`. This way, values at integer coordinates will repeat every Period units, and interpolation will ensure that resulting function is smooth.

Note, however, that this only works when Period is more than 1. So, to actually use this in making seamless textures, you'd have to sample a Period x Period square, not 1x1.
> 12 votes

# Answer
Though there are some answers here that would work, most of them are complicated, slow and problematic.

All you really need to do is use a *periodic* noise generation function. That's it!

An excellent public domain implementation based on Perlin's "advanced" noise algorithm can be found here. The function you need is pnoise2. The code was written by Stefan Gustavson, who has made a pointed comment here about exactly this issue, and how others have taken the wrong approach. Listen to Gustavson, he knows what he's talking about.

Regarding the various spherical projections some here have suggested: well, they in essence work (slowly), but they also produce a 2D texture that is a flattened sphere, so that the edges would more condensed, likely producing an undesired effect. Of course, if you *intend* for your 2D texture to be projected onto a sphere, that's the way to go, but that's not what was being asked for.
> 9 votes

# Answer
Another alternative is to generate noise using libnoise libraries. You can generate noise over a theoretical infinite amount of space, seamlessly.

Take a look at the following: http://libnoise.sourceforge.net/tutorials/tutorial3.html#tile

There is also an XNA port of the above at: http://bigblackblock.com/tools/libnoisexna

If you end up using the XNA port, you can do something like this:

```
Perlin perlin = new Perlin();
perlin.Frequency = 0.5f;                //height
perlin.Lacunarity = 2f;                 //frequency increase between octaves
perlin.OctaveCount = 5;                 //Number of passes
perlin.Persistence = 0.45f;             //
perlin.Quality = QualityMode.High;
perlin.Seed = 8;

//Create our 2d map
Noise2D _map = new Noise2D(CHUNKSIZE_WIDTH, CHUNKSIZE_HEIGHT, perlin);

//Get a section
_map.GeneratePlanar(left, right, top, down);

```

GeneratePlanar is the function to call to get the sections in each direction that will connect seamlessly with the rest of the textures.

Of course, this method is more costly than simply having a single texture that can be used across multiple surfaces. If you are looking to create some random tileable textures, this may be something that interests you.
> 6 votes

# Answer
Here's a much much simpler way to do tiled noise:

You use a modular wrap around for each scale of the noise. These fit the edges of the area no matter what frequency scale you use. So you only have to use normal 2D noise which is a lot faster. Here is the live WebGL code which can be found at ShaderToy: https://www.shadertoy.com/view/4dlGW2

The top three functions do all the work, and fBM is passed a vector x/y in a 0.0 to 1.0 range.

```
// Tileable noise, for creating useful textures. By David Hoskins, Sept. 2013.
// It can be extrapolated to other types of randomised texture.

#define SHOW_TILING
#define TILES 2.0

//----------------------------------------------------------------------------------------
float Hash(in vec2 p, in float scale)
{
    // This is tiling part, adjusts with the scale...
    p = mod(p, scale);
    return fract(sin(dot(p, vec2(35.6898, 24.3563))) * 353753.373453);
}

//----------------------------------------------------------------------------------------
float Noise(in vec2 x, in float scale )
{
    x *= scale;

    vec2 p = floor(x);
    vec2 f = fract(x);
    f = f*f*(3.0-2.0*f);
    //f = (1.0-cos(f*3.1415927)) * .5;
    float res = mix(mix(Hash(p,                  scale),
        Hash(p + vec2(1.0, 0.0), scale), f.x),
        mix(Hash(p + vec2(0.0, 1.0), scale),
        Hash(p + vec2(1.0, 1.0), scale), f.x), f.y);
    return res;
}

//----------------------------------------------------------------------------------------
float fBm(in vec2 p)
{
    float f = 0.4;
    // Change starting scale to any integer value...
    float scale = 14.0;
    float amp = 0.55;
    for (int i = 0; i < 8; i++)
    {
        f += Noise(p, scale) * amp;
        amp *= -.65;
        // Scale must be multiplied by an integer value...
        scale *= 2.0;
    }
    return f;
}

//----------------------------------------------------------------------------------------
void main(void)
{
    vec2 uv = gl_FragCoord.xy / iResolution.xy;

#ifdef SHOW_TILING
    uv *= TILES;
#endif

    // Do the noise cloud (fractal Brownian motion)
    float bri = fBm(uv);

    bri = min(bri * bri, 1.0); // ...cranked up the contrast for no reason.
    vec3 col = vec3(bri);

#ifdef SHOW_TILING
    vec2 pixel = (TILES / iResolution.xy);
    // Flash borders...
    if (uv.x > pixel.x && uv.y > pixel.y                                        // Not first pixel
    && (fract(uv.x) < pixel.x || fract(uv.y) < pixel.y) // Is it on a border?
    && mod(iGlobalTime-2.0, 4.0) < 2.0)                 // Flash every 2 seconds
    {
        col = vec3(1.0, 1.0, 0.0);
    }
#endif
    gl_FragColor = vec4(col,1.0);
}

```
> 5 votes

# Answer
I had some *not-bad* results interpolating near the edges of the tile (edge-wrapped), but it depends on what effect you're trying to achieve and the exact noise parameters. Works great for somewhat blurry noise, not so good with spikey/fine-grained ones.
> 3 votes

# Answer
I was checking this thread in search for an answer to a similar issue, then I got a clean and compact solution from the developer of this python code to generate fractal noise out of perlin/simplex noise. The updated code is provided in this (closed) issue and can be resumed in setting the gradients for the right side of the "generator" equal to those on the left side (and same for top and bottom), such as in

```
# Gradients
angles = 2*np.pi*np.random.rand(res[0]+1, res[1]+1)
gradients = np.dstack((np.cos(angles), np.sin(angles)))
# Make the noise tileable
gradients[-1,:] = gradients[0,:]
gradients[:,-1] = gradients[:,0]

```

Seems like an elegant and clean solution, I avoid copying the whole code here (since it's not my own solution), but it's available at the link given above. Hope this can be useful to someone looking to produce a tileable fractal 2d image like this one I needed, free of artifacts or distorsions.
> 1 votes

---
Tags: tiles, perlin-noise
---


# Question
Title: Algorithms for Automated Game Levels Creation ( 2D )?
I am trying to algorithmically create a game like the one in the picture below

I am trying to Create random levels from an algorithm.

Ideally, the algorithm will take into account the desired difficulty size and the board size ( N x N ) and produce a random map based on those 2 things.

I personally don't know how to determine difficulty in this game nor how to mathematically model it.

# Answer
> 2 votes
Generating a level is usually as simple as starting from a solved position and doing random moves backwards to get a randomized level.

Determining the difficulty is a lot harder, since everyone has a different background and will find the same level a lot easier or harder.

One thing I would try however is to train a neural network to spit out the difficulty, since it's much easier to get those to behave similar to humans as regular algorithms and they aren't very hard on computation. You will have to spend a couple of hours in front of it to get it to an acceptable level though, you may want to consider starting the game with an untrained one and "outsource" the task to users by using the solve time and move count to determine how hard the puzzle actually was.

---
Tags: mathematics, algorithm
---


title: Dividing Data and Logic in Unity

text:
# Question
Title: Dividing Data and Logic in Unity
I am currently working on a small side project (as usual), and trying to build up from previous experiences.

I have the following elements in the game: 1) `Region`: which contain a "food" target that has to be met 2) `Location`: Each region has a few location, where crops can be sown 3) `Crop`: A variety of crops with different effects

I currently have a system where I have a Region monobehaviour script that only considers the production of food from the crops. The location monobehaviour, stores the current state of the location, namely what crop is currently on it and how much food is currently available. I also have all the food production logic on that script. The crop scripts are scriptable objects with different food production rates and water consumption values.

I run into a problem when I started to want to add other types of elements to the location, or rather, have crops that don't necessarily produce food but have another effect on the game.

I decided to build another system, where instead of having the logic that triggers the various methods on the location script (for example the `ProduceFood()`, `SendFood()`, `ReceiveFood()`) within the location script itself or via hard links from UI elements.

This new systems is centred on `Action` scriptableObjects that can be added to the `Crop` scriptableobjects. The action script contains an `Act(Location loc)` method as well as a `SetUp(Location loc)` and Disable(Location loc). I can now customise how and when the `ProduceFood()`, `SendFood()`, `ReceiveFood()`, etc methods on the location script get called. For example the `ProduceAction` will add the `Act` method to a delegate event on the location script that triggers when a global `OnProduction` event gets triggered. Similarly, my hard UI links now point to a method on the location script called `UITriggerAction(int index)` which triggers the Act method registered to a delegate array on the location script.

Now each time a change the crop at a location I call the Disable method on all the Actions of the current crop, then I replace the crop and call the `SetUp` method on it, which will either register the associated Act method to the array accessible from UI, or to some other custom event.

The `Act` methods would be simple and look like:

```
Act(Location loc)
{
    loc.Produce();
}

```

or

```
Act(Location loc)
{
    if(loc.HasProduced())
    {
        loc.SendFood();
    }
}

```

By doing it this way I keep the variables specific to the location on the location script as well as the logic on it. In addition I avoid any dependency between the current crop at a location and the rest of the game. For example I could have a method from the `Region` script, that would check all the `currentFood` values on the locations, and it would still work even if the crop at that location doesn't impact the `currentFood` value at that location.

```
int AvailableFood()
{
    int availableFood = 0;
    for (i = 0; i < loactions.Length; i++)
    {
        availableFood += loactions[i].currentFood;
    }
    return availableFood;
}

```

I just control the way in which I call those methods using a more versatile system.

My question is: Is this likely to lead to a very messy code on the location script where I will have all the variables and all the methods to do everything?

Do you have any suggestions on how I can improve that system?

Supporting code:

```
class Location : MonoBehaviour
{

    Region parentRegion;
    Crop currentCrop;
    public int currentFood;
    int maxFood;

    public delegate CropAction(Location loc);
    public CropAction[] actions = new CropAction[6] // 6 possible actions accessible from UI

    public void UITriggerAction(int index) { actions[index](this);  }

    public void Produce() { // Do stuff   }
    public void SendFood() { // Do stuff   }
    public void RecieveFood() { // Do stuff   }
    public void UseWater() { // Do stuff   }
    public bool HasProduced() { return currentFood > 0;  }

    public AddCrop(Crop crop)
    {
        loc.Produce();
    }
}

```

# Answer
DMGregory is right. I'll offer some advice anyways, but in the future use the Code Review page.

What you are doing is called Data Driven Design. Some classic examples are Warcraft, Starcraft (1 and 2), and DoTA. I believe DoTA has done a full writeup on their system you can google. The cons of data driven design, is you give up a lot of public/private scoping because you need to query information everywhere. You also end up with a lot of if/elseif/else statements or switch statements. Good design can mitigate it but you'll still have more than a more OOP approach. The main pro of DDD is that things are insanely iterable and flexible. Extending / Modifying your design is done more via editor tooling than coding. In a large project where you can't possible code everything and maintain it, this is a good solution. It's also great if you want to expose an Editor to your users (like DoTA, Starcraft, and Warcraft).

Something you can do to help with the public/private dilema, is instead of exposing variables on Location that only Action may need you create an ActionContext struct, and pass that whenever you call Act. This also lets you get information from outside Location (like say current game score) you can just add that int to the struct. Whoever is calling the crop's Act method will be responsible for gathering that information. If it's the Game class then that's easy, you call a method on the Location class and pass the context with the data the Game class should provide. That method on the Location class adds it's information to the context then calls the crop. The crop adds it's information then calls Act on the action. You may also want to pass the Location class itself for brevity, but if you don't want to expose certain information on the Location class, make a struct field and have it fill out the struct. For example let's say we have a public interface for the Location class, and some private variables as well. Maybe we need one of those private variables, say "int privateVarA". Then you can make your context struct take an instance of a Location class, and an int "privateVarA". Now you can expose that private value to the action without having to expose it on the Location class as a whole.

public struct ActionContext
{
  // Required
  public Game game;
  public Location loc;
  public Crop crop;
  // Friend Variables
  public float RemainingCropGrowthTime;
  public float GameDifficultyCurve;
}

public void Act(ActionContext context) {
  // Do stuff
}
```

> 0 votes

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


# Question
Title: glReadPixels with GL_DEPTH_COMPONENT into PBO is slow
I need to read depth buffer back to cpu memory. It may be few frames old, so I use glReadPixels with a buffer bound to GL\_PIXEL\_PACK\_BUFFER. I use several buffers and ping-pong them. Finally, I read from the PBO with glGetBufferSubData. I have tried creating the buffers with GL\_STATIC\_READ, GL\_DYNAMIC\_READ and GL\_STREAM\_READ all with same results. Unfortunately, all this is still horribly slow.

```
class DepthBuffer
{
private:
    static const uint32 PboCount = 2;
    Buffer buffer;
    uint32 index;
    uint32 pbo[PboCount];
    uint32 w[PboCount], h[PboCount];

public:
    DepthBuffer();
    ~DepthBuffer();

    void performCopy(uint32 fbo, uint32 w, uint32 h);

    // returns 0..1 in logarithmic depth
    float valuePix(uint32 x, uint32 y); // pix in 0..(cw/ch-1)
    float valueNdc(float x, float y); // ndc in -1..1
};

DepthBuffer::DepthBuffer()
    : index(0), pbo{ 0, 0 }, w{ 0, 0 }, h{ 0, 0 }
{
    glGenBuffers(PboCount, pbo);

}

DepthBuffer::~DepthBuffer()
{
    glDeleteBuffers(PboCount, pbo);

}

void DepthBuffer::performCopy(uint32 fbo, uint32 paramW, uint32 paramH)
{
    // copy framebuffer to pbo

    glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[index]);
    if (w[index] != paramW || h[index] != paramH)
    {
        glBufferData(GL_PIXEL_PACK_BUFFER,
            paramW * paramH * sizeof(float),
            nullptr, GL_STREAM_READ);
        w[index] = paramW;
        h[index] = paramH;
    }

    glBindFramebuffer(GL_READ_FRAMEBUFFER, fbo);
    CHECK_GL_FRAMEBUFFER(GL_READ_FRAMEBUFFER);
    glReadPixels(0, 0, w[index], h[index],
        GL_DEPTH_COMPONENT, GL_FLOAT, 0);

    CHECK_GL("read the depth (framebuffer to pbo)");

    // copy gpu pbo to cpu buffer
    index = (index + 1) % PboCount;

    float *depths = nullptr;
    {
        uint32 reqsiz = w[index] * h[index] * sizeof(float);
        if (buffer.size() < reqsiz)
            buffer.allocate(reqsiz);
        depths = (float*)buffer.data();
    }

    glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo[index]);
    glGetBufferSubData(GL_PIXEL_PACK_BUFFER, 0,
        w[index] * h[index] * sizeof(float), depths);

    glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);

    CHECK_GL("read the depth (pbo to cpu)");
}

float DepthBuffer::valuePix(uint32 x, uint32 y)
{
    if (w[index] * h[index] == 0)
        return nan1();
    assert(x < w[index] && y < h[index]);
    return ((float*)buffer.data())[x + y * w[index]];
}

float DepthBuffer::valueNdc(float x, float y)
{
    assert(x >= -1 && x <= 1 && y >= -1 && y <= 1);
    return valuePix((x * 0.5 + 0.5) * (w[index] - 1),
        (y * 0.5 + 0.5) * (h[index] - 1));
}

```

The glReadPixels is taking all the time (on cpu). Am I doing something wrong? I thought that reading into the PBO should be asynchronous. Thanks.

# Answer
```
glReadPixels(0, 0, w[index], h[index], GL_DEPTH_COMPONENT, GL_FLOAT, 0);

```

Performance issues of this nature are typically caused by the OpenGL driver needing to do a format conversion during the read or write operation. Depending how the driver implements this format conversion, this could sometimes be as bad as needing to block all pending operations, copy the buffer off to CPU-side scratch memory, do the conversion on the CPU, then upload again to your PBO.

The trick here is to ensure that your glReadPixels parameters match the internal hardware format of your depth buffer; so for example, in your case if you had a D32F depth buffer then the glReadPixels call should copy directly without needing to go through an intermediate conversion. On the other hand, if you had a D24S8 depth/stencil buffer then, with the glReadPixels parameters you use, it would need to be converted.

You can experiemnt with different parameters to your glReadPixels call to determine the best fit for your depth buffer format.
> 1 votes

---
Tags: opengl, c++, performance, depth-buffer
---


# Question
Title: How can bays and straits be determined in a procedurally generated map?
I've got a procedurally generated map using Voronoi cells, with a defined sea level and a believable height map.

So far, I've been successful in labelling certain geographic features: land, ocean, lakes, rivers, estuaries, confluences, mountains, and biomes. Biomes include tundra, boreal forest, grassland, and temperate forest. There are also a couple other biomes there but for my purposes they aren't important right now.

I'd like to label bays, and straits next, but I'm at a loss on how to do this properly. A bay is a recessed, coastal body of water that directly connects to the ocean.

A strait is a naturally formed, narrow waterway that connects two parts of the ocean. Basically, where two pieces of land almost touch and there's ocean on both sides. Also called a "channel".

For determining features, I can loop through any feature by type like this:

```
for each (var feature:Object in geography.getFeaturesByType(Geography.LAND))
  // loop through lands
  for each (var cell:Cell in feature.cells)
  // loop through cells
    for each (var neighbor:Cell in cell.neighbors)
    // loop through a cell's neighbors
      trace(neighbor.hasFeatureType(Geography.LAND));

```

# Answer
> 30 votes
The way Dragons Abound identifies bays is to walk along the coastline and find two spots on the coastline where the straight-line distance between the spots is less than the distance along the coastline between the spots. This is the sinuosity of the coastline between the two spots. By selecting a sinuosity limit and limits for the straight-line distance between the spots you can identify narrow deep bays, wide shallow bays, etc.

In this picture, the red and purple dots show the two candidate points and the green line is the coastline between the points. The sinuosity is the ratio of those two lengths:

Alternatively, you can select two points on the coast and create a polygon by connecting the two points and the coastline between the two points (i.e., connect the green line above from red dot to purple dot). Measure the area of this polygon. A bay will have a larger area than a non-bay.

In my experience, a combination of these two measures was best for reliably identifying what people see as bays.

Note that this will also detect points. To find only bays, you need to check that the "inside" of the bay contains water and not land. A quick and easy way to do this is to check the midpoint of the line between the two points to see if it is water. (This can be fooled but is generally sufficient.)

A related problem is to identify the "mouth" of the bay -- i.e., the best choice for the two points that mark the opening to the bay. Typically you'll have a bunch of candidates for the "mouth". In the example map above, you could put the mouth of that bay further in or further out. Generally speaking it probably doesn't matter too much, but one heuristic that works reasonably well is to minimize the straight-line distance across the mouth.

I haven't done straits yet, but my intuition is to check points along the coastline to find the closest point on any other coastline; if that is under some set limit it is a strait.

# Answer
> 48 votes
Here's a rough idea using image processing transformations to isolate the features of interest:

1. Apply a flood fill from an ocean cell to make a mask of all ocean cells. Depending on how your rivers are set up, you might need an extra elevation or clearance criterion to keep the ocean mask from flowing inland. ;)
2. Apply a local smoothing to the edge of this mask, keeping the connectedness/topology the same, but smoothing out small noisy coastline features that can be distracting. This lets us focus on big bays over tiny inlets. You can use the width of your filter kernal / number of iterations to finely control the scale of features you preserve.

Here I applied a median filter a few times. Cellular automata are another popular way to erode smooth shapes from a noisy input.
3. Turn the mask into a distance field, where each cell stores its distance from the smoothed coastline.

Now we see some promising feature highlights. In a signed distance field, both bays and straits show up as sharp ridges, with distance falling off to the sides. We can use an edge detection filter to pop out these ridges:

You can then distinguish between bays and straits by following the ridge to determine its connectivity. A bay is a ridge that runs toward the coast, getting shallower and shallower (in distance from land) until it ends in a point. A strait is a ridge that connects a high-distance region to another high-distance region, going through a lower-distance region along the way.

Or, another way is to assign each island an ID (connected component search), then when you're making your distance field, propagate "closest island ID" alongside the distance frontier. A bay or inlet is then a ridge in water adjacent to the same landmass on both sides, while a channel is a ridge that separates water adjacent to two different landmasses.

You can set minimum & maximum distance-to-shore or length-of-ridge constraints to control which features to label, if you need to exclude excessively narrow/wide straits for instance.

# Answer
> 6 votes
Basically, you need to think about what you mean, precisely, by a bay or strait, and why you want to differentiate them (is it for AI calculations, or to label landmarks, or something else?). Play around with a few definitions to find the one that looks best to you. Then, formulate conditions to check on your Voronoi cells. A few suggestions:

# Bay

* Any ocean cell that only connects to a single other ocean cell
* OR: Any ocean cell that connects to more land than ocean cells, with all ocean cells next to each other
* OR: Same as above, but with a criterion based on border length (e.g. twice as much land as water border)

# Strait

* Any ocean cell that connects to exactly two ocean cells which are not next to each other
* OR: Any ocean cell that connects to two land cells that don't belong to the same landmass (you need to find out which land cells are connected first, and assign IDs to each landmass)
* OR: March around the border, and count land/water and water/land transitions. You need at least two of each.
* Depending on your method and what you want to do with the categories, you might want to eliminate straits that only lead to a bay, or label them as bay instead.

---
Tags: procedural-generation, maps, graphics-programming, simulations
---


# Question
Title: How to determine what difficulty is right for the game?
I am targeting mass casual audience as I am developing the hyper-casual game. The problem is that I have played **Helix Jump** and **Color Bump 3d** and those games have a **pretty big difference in difficulty level** (well at least for me). They are both considered hyper-casual, both target mass casual audience and both have market success.

If two so similar games have such decent difference in difficulty **how to determine that the difficulty of my game is just right?** *It's easy to say that it's subjective* but when you invest so much time in your project you need to have at least **some benchmark to work with**. How to define this benchmark?

# Answer
> 13 votes
Playtest, playtest, playtest.

Get testers from your target demographic, let them play the game, and see which parts of the game are so difficult they are frustrating and which parts are so easy they are boring.

Get new testers from time to time which are not yet familiar with your game ("kleenex testers") so they tell you the difficulty from the perspective of a new player.

---
Tags: game-design, difficulty
---


# Question
Title: Is there a tried-and-true method for calculating or detecting the edges of platforms?
In terms of a simple 2D platformer, I was wondering if, over the years, a *right way* has emerged as far as determining whether or not a strolling character has reached the edge of the platform it is walking on.

My searches haven't produced an answer for this question and there does not seem to be a consensus about what the best way is, but I would like to believe that there **is** a best way considering the classic nature of the 2D platformer.

Working with Godot 3.0.6 Mono, my current idea is two trace two rays from either side of a character's collision box downward, where a difference in the length (assuming flat platforms) between those two rays before collision means the character is partially over an edge. However, I feel like this can get intense if lot's of characters are being managed every frame. What are some other ways of approaching this? Any other suggestions are appreciated.

# Answer
> 1 votes
The "easy cheesy" way is just to use colliders. Obviously, that method is... quite terrible. Evolving from that, other than a regular capsule collider for the character, you can add a small collider at the feet of your character (this one should be trigger / overlap collider). Still... not very good.

The best way that I have personally seen in action is pretty much what you described. Use rays, and depending on how precise you need it to be, you can use just one (that is pretty much just detecting whether you are standing on the ground or not), two from each side or even bigger number in regular intervals. A good idea is to use "skin width", aka starting the ray a bit "inside" the character. (in this case, your starting point would be few cm above the floor). If you use the rays directly from the bottom, in some engines the detection might be a bit wonky.

The "multiple rays" method is also good for detecting slopes, and even for regular collisions. Maybe they fixed it in the meantime, but I remember that Unity had a big problem with colliders, for example your character could be stuck to the wall if you jumped and moved towards the wall at the same time. Using rays fixed the problem for me :)

Edit: First, thank you for the upvote. Second, while writing the answer I totally forgot the main reason I wanted to answer:

If you are scared about the optimization, you can use a couple of tricks. First, only use this method with the main character. Make all the NPC's use "just" gravity, or a less precise method (maybe just two rays for the NPCs, and 5 for the main char?)

Also, you can only check it whenever the character has moved. If you don't include stuff like breakable floor, there should be no issue with it at all. That will drastically reduce the number of calls!

---
Tags: 2d, ai, platformer, npc
---


# Question
Title: How to store the progress of multiple users
When I start my game, it displays a level menu, and When I select a level, it's gonna create a game corresponding to the level and I can play. Now I'd like to store the progress of each user, implementing something like this but I don't know where to start.

```
public class Game {

    private Level level;
    // Each level are stored in a txt file,
    // the class Level read and load the file.

    public Game(Level level) {
        this.level = level;
    }

// Other methods.. such as Undo, restart etc...

}

```

I have created a login system in a class called User where it stores the data in a map.

And I need a class that link them so I created a new class but I'm not sure what kind of method it should contain :

```
public class MoveTheBlock{

    private User currentUser;

    public MoveTheBlock() {

    }

}

```

# Answer
> 2 votes
It seems to me that your problem is in two "layers".

Layer one is just coding the solution: I'm not sure what "move the block" class is supposed to do, I just assume is the main class game? If that's the case, it should have methods for handling input. For example: MovePlayer, CollectPickup, MoveBlock. Also methods that relate to the general gameplay, like checking if the player has scored somehow, or did the game end due to time being finished?

If MoveTheBlock is supposed to be the save game file, it should have at least a method to save the game, and to load the game. Save would take all the save'able info from the game, like player score, position, maybe position of items if they are movable? And then, put it into a single object and store it into a file. If you want to make that easier, you might want to look up "serialization".

With that being said, the best way to handle it is to do the tasks one by one, and look for solutions to each problem.

The second layer of your issue is the whole project organization. That is something that comes with practice - try to think in terms of object oriented programming. People often compare code to cars, and it's a good idea. A car has many parts, and every single part has one responsibility. The engine, the tires and steering wheel - and they only "connect" where and when it's needed.

You should try to organize your program in the same way. You might have a player. A block. A timer. Ask yourself what are they supposed to do, and what other elements they have to communicate with.

Something that helps me with that, is thinking of the core gameplay loop. Always try to think of making a working game first, and then start worrying about other things, like saving the game.

I'm sorry for blabbering - I tried to keep my answer short. It would really help us if you provided more details about your game :)

# Answer
> 0 votes
The way I have handled this is to have two classes: one for saving and loading (call it Save); one for just holding the information (Object). Save needs two methods: one to load previously saved information by reading Object; one to save information by writing to Object. The load method is triggered when a user signs in. The information from Object is loaded and the level screen is displayed. The save method is called when a level is completed or when settings are changed.

Object is just a serializable two-dimensional array. It holds user names, levels they have completed, scores for those levels and preferences, such as sound enabled and music enabled.

---
Tags: java, savegame
---


# Question
Title: Find friend groups in a virtual social graph
In my game, "people" form bonds through common interests. A person may have 1 or more interests, and a certain weight (0f - 1f) attached to it. Every now again, when 2 people are close to one another, relationships are formed based on common interests. E.g., if I have interests such as "Movies, Cheese, and Art", and you have "Movies and Cheese", then we have a pretty strong bond.

This is all working great, and over time, all the people in my game have some sort of bond with others.

What I'd like to do now, is construct social groups in a somewhat efficient manner (my game has an asynchronous task manager, so if the calculation is somewhat heavy, it's not a show-stopper). My current theory is to pick a person, look at his or her relationships, and then try to slowly build a graph to match as much like-minded people as possible.

I'm not 100% sure how to do this. I was thinking of comparing interests with common friends, but wondered if there was a better way? Currently relationships are stored as a person identifier, and then a list of (up to) 5 relationships, which contain their identifier, plus the weight.

The end result that I'd like, is a bunch of "groups" of like-minded people, that have been fed from this initial map.

What I'm looking for needs to be quite performant (with the caveat that I do have an asynchronous task manager), but the end result is that over time, social groups are constructed within which are people best suited to "hang out" with one another, based on their shared interests.

# Answer
> 3 votes
This sounds like a graph clustering problem.

Given a graph of nodes (people), and edges (bonds/relationships), where edges have weights (relationship strength), you want to split it into disjoint subgraphs (groups of people where no person is in two different groups), such that the level of connection inside each group is in some sense "higher" than the connection between groups.

How we define this "higher" level of connection will determine what algorithms we use, and what kinds of groups we get:

## A) Group the strongest relationships first

This approach leads to Kruskal's Algorithm \- often used for finding a minimum spanning tree of a graph, but it can be stopped early to produce clusters instead.

Here you start with everyone in their own solo group.

Sort all your bonds by strength, then walk through the list from strongest to weakest, looking at each bond in turn.

If the two people sharing that bond are already in a group together, skip it and move on.

Otherwise, if the two people are in different groups, merge the two groups into one group containing all the members of each.

Stop once you hit a bond you consider too weak to unite a group, or once you're down to a desired number of groups.

This is simple to code up and with appropriate disjoint set data structures is very fast - the initial edge sort is the most expensive part (\\$O(E \cdot \log E)\\$). But it can produce "tenuous" groups, where individual members each share a strong bond with at least one other member, but might have no connection at all with more distant members in the same group.

## B) Find groups where everyone shares a strong bond

To counter this, we might insist that everyone in the group should have a strong relationship with everyone else in the group. In graph theory terms, this means they form a "clique," and finding them entails the NP-Complete "Clique Problem," so you can expect to work harder to find these. Exact algorithms run in exponential time, though there are more modest approximation algorithms you can try.

You can either convert your graph to an unweighted one by discarding all relationships below a threshold strength, to use algorithms that look for cliques with the largest number of members, or keep your weights and use algorithms that look for cliques of maximum total weight.

Depending on how you define which bonds are strong enough to count, you might find your graph contains very few, small cliques of just a handful of people - since two people knowing each other only as "a friend of a friend" is enough to block them from both being members of the same group.

## C) Allow friends-of-friends

We can relax our clique criterion to say it's OK if not everyone in the group knows everyone else directly, as long as they know someone who knows them. In graph theory terms, we're looking for "subgraphs of diameter 2", where any two members of the group are separated by at most two relationships with a mutual friend in between.

We can find groups like these with a Highly-Connected Subgraphs clustering algorithm. Here again, we'd discard relationships below a threshold strength to convert our graph to an unweighted one. We then repeatedly search for a minimum cut, the smallest bundle of edges we can slice to split the graph into two. As long as there are fewer than half as many edges in the minimum cut than nodes in our group (the connection from one side of the group to the other is "weak enough"), we slice those edges out and repeat on each of the two subgraphs.

This animation by Fredseadroid via Wikipedia shows the algorithm in action.

This looks to me like it gives a good compromise between the tight connections of a clique and the six-degrees-of-separation chains of a Kruskal cluster, as well as intermediate complexity to compute (roughly \\$O(n^2)\\$ to \\$O(n^3)\\$ depending on the min-cut subroutine you choose).

---
Tags: c#, algorithm
---


# Question
Title: How to change 100 GameObjects' color without pushing RAM to hard?
I'm developing a mobile game and one of the gamemodes has 100 gameobjects(basic cubes). And they all have same material. I need to know how to change their color one by one with script.

I'm not very good at programing, so only idea that i have for this situation is declaring 100 objects to var, and then change their color one by one.

But like a said it's a mobile game so i need to do it with simplest code so performance would be perfect.

# Answer
Having 100 game objects with 100 behaviours each one running an own update function isn't actually that much, even on mobile. There might be some performance to gain by using the rather new Entity - Component - System architecture, but intuitively I am not that sure that this will even be necessary.

What could, however, become a bottleneck is if you update the color of each cube with `GetComponent<Renderer>.material.color = new Color(r, g, b)`. Whenever you modify the material of a renderer, you actually create a completely new material in memory and assign that new material to this one object. This also breaks certain optimizations the rendering engine can do when multiple objects share the same material.

When you end up with 100 cubes which each have their very own material, then you might indeed run into performance problems.

So what should you do instead? That depends on what you actually want to do.

* If the number of colors you want is limited, then you could create a different material for each color and exchange those material assets.
* If all the cubes are supposed to change their color at the same time, you can access the `.sharedMaterial` of one of them to also change all the other (which of course won't work if you already broke the material sharing as described above)
* If you want to assign arbitrary colors to each cube, use `renderer.SetPropertyBlock`. This very useful method allows you to override just a few settings of a material on a per-renderer base without breaking the draw call optimization you got from sharing materials.

Example code:

```
MaterialPropertyBlock properties = new MaterialPropertyBlock();
properties.AddColor("_Color", new Color(r, g, b));
GetComponent<Renderer>().SetPropertyBlock(properties);

```
> 0 votes

# Answer
It's really hard to give advice with so little information about the language and what exactly you are trying to do. But still, there's some ideas you could like:

A comment here mentioned that you can use an empty object (you can call it CubeMaterialManager for example), and you can store the reference array in it.

If the cubes are created dynamically, you can add them to the array while they are created. If they aren't, you can use something along "find all objects of class", but that's usually not recommended.

You can most probably add a tag to the object and search by that. And if you know that they are located in some proximity, you can even use some kind of collision to find them (in UE4 it would be MultiSphereTrace).

You didn't mention if all the cubes will change to the same color. If they will all have a different color, the CubeMaterialManager can store another array with the new materials. Then just go through the loop.
> 0 votes

---
Tags: unity, android, ios
---


# Question
Title: Is IDirectInput8::FindDevice totally broken on Windows 7?
I'm developing on Windows 7, and using DirectInput8 for my input needs.
I'm tracking gamepad additions and removals (that is, `GUID_DEVINTERFACE_HID` devices) using the `DBT_DEVICEARRIVAL` and `DBT_DEVICEREMOVECOMPLETE` messages, which works fine.

However, what I've come to find out is that no matter what I do, passing the received values from `DBT_DEVICEARRIVAL` to IDirectInput8's FindDevice method, it will **always** fail to identify the device, returning `DIERR_DEVICENOTREG`.

DirectInput still clearly knows about the device, because I can enumerate and create it just fine.
I've tried with three different gamepads, and the error persists, so it's not about that either.
I also tried passing some alternative interface GUIDs for the `RegisterDeviceNotification` call, didn't help.

So, has anyone else faced the same problem, and have you found a usable workaround?
I'm afraid I'll soon have to stoop down to re-enumerating all devices when something is added or removed, but I'll first give this question one last shot here.

EDIT: For the record, I've also tried pretty much *every single* HID API & SetupAPI function for alternative ways of figuring out the needed GUIDs, with zero success. So if you're facing the same problem as me, don't bother with that route. I'm pretty sure those GUIDs are made up by DirectInput itself somehow. Short of reverse engineering dinput8.dll, I'm truly out of ideas now.

# Answer
> 1 votes
I see the issue in a similar vein.

Regardless of which version of DirecitInput is used on a 64 bit system you get `DIERR_DEVICENOTREG` on calling `lpDI->CreateDevice(*lpGUID, &lpDID, NULL)` and I use GUIDs that `lpDI->EnumDevices(0, dienumgetrval, name, DIEDFL_ATTACHEDONLY)` has returned.

Doesn't matter if I use DirectInput8Create or older code. Same code on a 32 bit system appears to function. Of course, the previous version of this code still works and it links to DirectX 7 DLLs and the new version is all DX9 so I'm betting that's where things are busted.

Still looking for a work around as DirectInput is jettisonable long before DX9 is.

EDIT: Looks like it's only when run in the IDE that I get DIERR\_DEVICENOTREG errors. Course that makes debugging stuff really a challenge but maybe there's a regsvr32 fix for the IDE (VS 2005): http://blogs.msdn.com/b/oldnewthing/archive/2011/02/10/10127054.aspx

EDIT2: Results are all over the place depending on whether you use Dinput8 or older stuff or 64 bit OSes (oddly win8.1 works well under all circumstances, go figure). But as near as I can tell quirky results seems to be limited to the mouse and keyboard and if you use the system kludges GUID\_SysKeyboard or GUID\_SysMouse instead of the GUIDs returned by the enumerator it works. But I'm not guaranteeing I don't have to put a WM\_INPUT path and deal with RAWINPUT into the software before too long...

# Answer
> 1 votes
In case someone is trying to find any clue. Try use `GUID_DEVINTERFACE_HID` for `RegisterDeviceNotification()` and use `GUID_HIDClass` for `IDirectInput8::FindDevice()`.

IDirectInput8::FindDevice Method API document is **not true** any more

> The application obtains the class GUID from the device arrival notification.

# Answer
> 0 votes
I've faced the same problem sometimes. So far I couldn't find an workaround. But there's a solution, it may be complicated but it was worth ( well for me ). I've been using raw input ( Windows DDK is needed ), within the end, I had a little but powerfull and usefull framework.

In order to understand raw input I've been following a german tutorial:

http://zfx.info/viewtopic.php?t=2977&p=38152

If you don't understand german, then you could just rather follow MSDN with it's documention, even if it's harder at the beginning.

# Answer
> 0 votes
Finally found the solution after using the system GUID workaround but having people with international keyboards forced me to reexamine the issue. Turns out with earlier versions of DI when you enumerated devices you could take pointers to the GUIDs and they would still be good when you call CreateDevice. Turns out that's no longer the case. You actually have to copy the GUIDs away and then pass those copies.

---
Tags: windows, directinput
---


# Question
Title: What is the purpose of multi-staged levels in mobile games?
In most recent mobile games like **Grass Cut**, **FireBalls 3D**, **Twist Hit!** or **Snow Drift!** I see the same level structure where you need to finish **3-4 mini-levels / stages** in order to really finish **the level**.

For example, in **Grass Cut** average time to finish a **full level** that consists from **4 mini-levels / stages is 4 minutes**. That's a very long play session as to mobile. **What's the purpose of those stages?** Why can't they just create a full-featured levels from those stages like in **Color Bump 3D**?

# Answer
> 2 votes
One mechanical reason to break levels up into multiple parts is to provide a mental break for the player, allowing them to reset their concentration or to provide a clear pausing point for them in case they need to put the game down and attend to other aspects of life.

A similar reason would be to provide more of a sense of accomplishment and progression. Providing goals to complete that are part of a larger goal, even if the scope of both is small, provides both positive reinforcement to the p layer upon completing each smaller goal *and* a bit of a carrot to keep the player engaged when it looks like the *next* goal is close at hand. It helps with that "well I'll just finish *one more* task before I put this down" feeling.

Another reason to break levels up into stages is for thematic reasons, to have a clear transition between environments, ideas, or concepts (but one that still fits within the *overall* theme of the outer level structure). This is more common in narrative-based games; you might also see cutscenes used to break up these stages.

---
Tags: game-design, mobile, level-design
---