# Question
Title: libGDX game crashes on Android without any logs / errosrs
libGDX game crashes without any errors in console on android devices. It happens at different parts of game at different screens at different time. I don't see the reason. Game works well, without freezing. The game does not crash under resource-intensive operations like changing the screen, but already when the screen is loaded and the player plays for a while. The use of memory would probably be normal, based on the graphs of the use of RAM. The CPU is also not overloaded.  The strangest thing is that when a game crashes there are no errors displayed in the console. The phone screen turns black for a while, then the system emits on the home screen.The phone also does not show error messages in the application, etc. Also, sometimes after displaying the AdMob video, the game stops responding to the input, although the graphics continue to work, the animations are working.

At first I thought it might be due to AdMob's incorrect implementation. But after the complete removal of AdMob from the project, the problem did not disappear.

What then can lead to such behavior of the application?

Perhaps this is due to some error in AssetManager? I would like to note that I use a large number of textures (more then 170), packed in an atlas. All textures in atlas takes *4.31MB* disk space and all my assets takes *6.2MB.* All the resources I load during the initial loading of the game using AssetManager.

So, my **Res** class:

```
public class Res {

    public static final String LOCALE_BUNDLE_PATH = "i18n/locale";

    public static final String MAIN_ATLAS_PATH = "packs/main/MAIN.atlas";
    public static final String MUSIC_M3_THEME_PATH = "music/atc_m3_theme.mp3";
    public static final String KICK_SOUND_PATH = "music/atc_kick.mp3";
    public static final String FADEIN_SOUND_PATH = "music/atc_fadein.mp3";
    public static final String DRAG_START_SOUND_PATH = "music/atc_drag_start.mp3";
    public static final String DRAG_STOP_SOUND_PATH = "music/atc_drag_stop.mp3";

    public static final String FONT_REGULAR_PATH = "fonts/comfortaa_regular.ttf";
    public static final String FONT_LIGHT_PATH = "fonts/comfortaa_light.ttf";
    public static final String RUSSO_ONE_REGULAR = "fonts/russo_one_regular.ttf";

    public static TextureAtlas MAIN_ATLAS;

    public static I18NBundle LOCALE;

    /* MUSIC & SOUNDS */
    public static Music M3_THEME;
    public static Sound KICK_SOUND;
    public static Sound FADE_IN_SOUND;
    public static Sound DRAG_START_SOUND;
    public static Sound DRAG_STOP_SOUND;

    private Res () {
        MAIN_ATLAS = null;
    }

}

```

And my **ResManager**:

```
public class ResManager extends AssetManager {

    public void loadResources () {
        load(Res.MAIN_ATLAS_PATH, TextureAtlas.class);
        load(Res.MUSIC_M3_THEME_PATH, Music.class);
        load(Res.KICK_SOUND_PATH, Sound.class);
        load(Res.FADEIN_SOUND_PATH, Sound.class);
        load(Res.DRAG_START_SOUND_PATH, Sound.class);
        load(Res.DRAG_STOP_SOUND_PATH, Sound.class);
        load(Res.LOCALE_BUNDLE_PATH, I18NBundle.class);
        finishLoading();
        Res.MAIN_ATLAS = get(Res.MAIN_ATLAS_PATH, TextureAtlas.class);
        Res.M3_THEME = get(Res.MUSIC_M3_THEME_PATH, Music.class);
        Res.KICK_SOUND = get(Res.KICK_SOUND_PATH, Sound.class);
        Res.FADE_IN_SOUND = get(Res.FADEIN_SOUND_PATH, Sound.class);
        Res.DRAG_START_SOUND = get(Res.DRAG_START_SOUND_PATH, Sound.class);
        Res.DRAG_STOP_SOUND = get(Res.DRAG_STOP_SOUND_PATH, Sound.class);
        Res.LOCALE = get(Res.LOCALE_BUNDLE_PATH, I18NBundle.class);
    }

}

```

I know that in an android ecosystem doing TextureAtlas static is a bad idea, but for the convenience of using resources in the code, it had to be done. In addition, it is still deleted from memory, because I kill the process while the application is shutting down.

```
@Override
    protected void onDestroy() {
        android.os.Process.killProcess(android.os.Process.myPid());
        super.onDestroy();
    }

```

Also, I do the correct dispose of all screens, obviously pointing GC to unnecessary objects that he should has collected. For example:

```
@Override
    public void dispose() {
        stage.dispose(); // Stage
        loadingPane = null; // Group
        multiplexer = null; // InputMultiplexer
        firstScreen.destroy(); // Group
        secondScreen.destroy(); // Group
        firstScreen = null;
        secondScreen = null;
        bgSky = null; // Image
        ground = null; // Image
        dialogCircuit = null; // Group
        dialogModule = null; // Group
        dialogNotEnough = null; // Group
    }

```

Tried to catch memory leaks with the help of LeakCanary. But it did not work. The log is empty.

Tell me, what could be the reason? A very annoying problem that kills all the joy of using my game.

# Answer
> 0 votes
Solved. Answer here.

(The problem was in very frequent `BitmapFont` generation.)

---
Tags: libgdx, android, asset-management
---


# Question
Title: How to add space in inspector in nested object to a field(property) with PropertyAttribute
I use `GUILayout.Space(px)` to add space after some property. Property is drawn using `PropertyDrawer` via `PropertyAttribute`.

You can see that `Min Max Prop` displays properly inside `targetObject`(AudioPlayer) but if it's in nested object like `Engine, Engine Multi, Filed` it adds space to the `targetObject` not the nested object itself.

# Answer
> 1 votes
It is possible in nested objects by adding height to overridden `GetPropertyHeight()` of `PropertyDrawer`.

```
namespace Kimo.Assistance.UTILITY
{
#if UNITY_EDITOR
    [CustomEditor(typeof(MultiSupportPropertyAttribute))]
    [CanEditMultipleObjects]
    public class MultiSupportPropertyAttributeDrawer : PropertyDrawer
    {
        private MultiSupportPropertyAttribute _attribute;

        public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
        {
            if (this._attribute == null)
                this._attribute = this.attribute as MultiSupportPropertyAttribute;

            return base.GetPropertyHeight(property, label) + this._attribute.GetPropertyExtensionHeight();
        }

        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
        {
            //foreach (var attribute in fieldInfo.GetCustomAttributes(false))
            //{
            //  (attribute as MultiSupportPropertyAttribute).DrawInInspector(position, property, label);
            //}

            this._attribute.BeginDrawInInspector(position, property, label);
            this._attribute.DrawInInspector(position, property, label);
            this._attribute.EndDrawInInspector(position, property, label);
        }
    }
#endif
}

```

`GetPropertyExtensionHeight()` \- is my method that needs to be overridden. It just adds some space instead of giving a full new space size.

```
public override float GetPropertyExtensionHeight()
{
    if (this._compactFormat)
        return InspectorUtility.DEFAULT_FIELD_HEIGHT;
    return 0;
}

```

Works like a charm:

---
Tags: unity, gui
---


# Question
Title: Procedural dungeon algorithms for a more open dungeon
I'm working on a game that I want dungeon generating in, but I plan on having ranged weapons in it, so I want it a bit more open. I'd like to avoid corridors and I don't want to use a grid of custom rooms.

I don't want to use perlin noise and make it like random blotches, so that's not an option.

All I need is a summary of how the ideal algorithm for this works.

EDIT: Something that gives a result like this:

It doesn't need to be so rounded. The point is that there aren't really corridors.

I'm also fine with a modular approach where the areas are hand made as long as it's still not on a grid. The issue is that if it's not on a grid, the areas are normally connected by corridors.

EDIT2: I made this a while ago, which works when it comes to shape, but it works with a modular system and it looks like this because I intentionally put rooms on top of other rooms. This causes problems if I start decorating the rooms and filling them with interesting stuff.

# Answer
> 1 votes
What you're asking for is more of a feature or aspect of a procedural dungeon generator, rather than a generator itself. There are two ways to achieve more spacious layouts:

## Generate spacious features

Are you using a traditional rooms-and-corridors generator? Instead of digging 1-tile-wide corridors, **create wider corridors**1. Adjust other features too, like **wider doors**.

Does your generator place random obstacles or walls onto open space? Ensure that there is **enough space around the obstacle**, so you do not create narrow passages.

Having such features ensures that you do not generate cramped layouts in the first place.

Another method is to run a generator on a **larger scale**. This would naturally create spacious layouts. Then add fine details to mask the scale.

## Modify/reject closed layouts

Are you using a generator where it's difficult to avoid cramped spaces, like a noise-based generator (e.g. Perlin)? You can deal with this by **detecting cramped features**, and either modify the layout (e.g. **enlarging the choke-points**) or **reject the layout** entirely and generate again using a different random seed.

There are different ways to detect cramped features, like this one.

You could also accept some cramped areas and go for a good-enough approach. The cellular automata algorithm is generally good at avoiding 1-tile-wide features.

---

1 Example here. This algorithm generates corridors that are 3-tiles-wide.

# Answer
> 1 votes
When you want to generate cave-like maps, you should usually use a cellular automata. You can find the long version here, but I'll summarize it.

First, the map is filled in randomly with walls and air, then for each wall or air, you check how many of its neighbours are walls. If the current tile is a wall, and there are at least 4 other walls around it, then it stays the same, otherwise it turns into air. If it's air and has at least 5 wall neighbours, then it becomes a wall, otherwise it stays air.

After you repeat this for every tile multiple times you get a pretty organic looking map. It might have multiple sections (open spaces) in it though. To circumvent this, try using a floodfill alogorithm on every unchecked air block, and if it finishes, but leaves other air blocks on the map, then that means there are multiple rooms. Try finding them and either connecting them or filling the smaller one in with walls.

---
Tags: procedural-generation, random, procedural
---


# Question
Title: Everything after the yield return new wait for seconds is not runnung Unity
I am trying to add a delay to the respawn of my player. But when I add the yield return new line nothing runs after it. I have tried addiing debug.log after everyline and they stop out putting once they get to the yield return new line. This respawn is on the player on its own script and there is no other script that would effect the player respawn. The game is also 2D. Here is the code

```
public GameObject spawnPoint;
public float respawnDelay = 2;

public IEnumerator RespawnPlayer()
{
    gameObject.SetActive(false);
    gameObject.transform.position = spawnPoint.transform.position;
    yield return new WaitForSeconds(respawnDelay);
    gameObject.SetActive(true);

}

void OnCollisionEnter2D(Collision2D other)
{
    if (other.gameObject.tag == "Enemy")
    {
        StartCoroutine(RespawnPlayer());
    }
}

```

Thanks!

# Answer
Coroutines run only on active GameObjects. Turning off the script's own GameObject with SetActive(false) means none of its component messages will be called, and all of its coroutines will be terminated. So your coroutine never has a chance to wake it back up.

You'll need to put the timer on something else. Worst-case, you could delegate this to an external timekeeper.

```
public class Sandman : MonoBehaviour {

    static Sandman _instance;

    public static Coroutine SleepFor(GameObject sleeper, float duration) {
        if(_instance == null)
            _instance = new GameObject("Sandman"). AddComponent<Sandman>();

        return _instance.StartCoroutine(SleepCoroutine(sleeper, duration));
    }

    static IEnumerator SleepCoroutine(GameObject sleeper, float duration) {
        sleeper.SetActive(false);
        yield return new WaitForSeconds(duration);
        sleeper.SetActive(true);
    }
}

```

Now when your script needs a nap, it can ask the Sandman,

```
Sandman.SleepFor(gameObject, 2f);

```

And the Sandman will be responsible for watching the hourglass while your GameObject sleeps.
> 4 votes

# Answer
Because for a Coroutine to run, it needs the GameObject having the MonoBehaviour responsible for calling the coroutine to be active. At the start of the IEnumerator, you deactivate the GameObject, from there the coroutine doesn't run anymore.

As you can see on this **post**, it just needs the GameObject to be active, not the script, so the most you can do is to disable the script, and use a transparent shader.

Or... you could call the coroutine from a persisten GameObject you'll know you won't ever disable. Example:

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

public class CoroutineController : MonoBehaviour
{
    public static CoroutineController Instance;

    void Awake()
    {
        if(Instance == null) Instance = this;
        else if(Instance != this) Destroy(gameObject);
    }

    public void Wait(float _seconds, Action onWaitEnds)
    {
        StartCoroutine(WaitCoroutine(_seconds, onWaitEnds));
    }

    private IEnumerator WaitCoroutine(float _seconds, Action onWaitEnds)
    {
        yield return new WaitForSeconds(_seconds);
        if(onWaitEnds != null) onWaitEnds();
    }
}

public class YourClass : MonoBehaviour
{
    public float waitTime;

    public void WaitAndReappear()
    {
        gameObject.SetActive(false);
        CoroutineController.Instance.Wait(waitTime,
        => { gameObject.SetActive(true); });
    }
}

```

Here you should make use of **Lambda Expressions** to make something after the wait. I hope it helps.
> 1 votes

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


# Question
Title: Locking value when creating tweaking dependent values
I have several values which adjust them self In Unity Inspector when I tweak one of them. So total sum of these values stays constant. (which is 100 as 100%)

Sometimes it is hard to get specific values on more when one slider. How can I lock value so it can't be affected by adjusting other values?

```
private const float TOTAL_STARS_SHARE = 100.0f; //total share of all stars

// #0
[Tooltip("Share of Blue Star Hard prefabs in percentages.")]
[Range(0f, 100f)]
[SerializeField]
private float shareOfBlueStarHard;
private float shareOfBlueStarHardCACHE; //cache for value with same name

// #1
[Tooltip("Share of Blue Star Medium prefabs in percentages.")]
[Range(0f, 100f)]
[SerializeField]
private float shareOfBlueStarMedium;
private float shareOfBlueStarMediumCACHE; //cache for value with same name

// #2
[Tooltip("Share of Blue Star Soft prefabs in percentages.")]
[Range(0f, 100f)]
[SerializeField]
private float shareOfBlueStarSoft;
private float shareOfBlueStarSoftCACHE; //cache for value with same name

// #3
[Tooltip("Share of Red Star Soft prefabs in percentages.")]
[Range(0f, 100f)]
[SerializeField]
private float shareOfRedStarSoft;
private float shareOfRedStarSoftCACHE; //cache for value with same name

// #4
[Tooltip("Share of White Star Hard prefabs in percentages.")]
[Range(0f, 100f)]
[SerializeField]
private float shareOfWhiteStarHard;
private float shareOfWhiteStarHardCACHE; //cache for value with same name

// #5
[Tooltip("Share of White Star Medium prefabs in percentages.")]
[Range(0f, 100f)]
[SerializeField]
private float shareOfWhiteStarMedium;
private float shareOfWhiteStarMediumCACHE; //cache for value with same name

// #6
[Tooltip("Share of White Star Soft prefabs in percentages.")]
[Range(0f, 100f)]
[SerializeField]
private float shareOfWhiteStarSoft;
private float shareOfWhiteStarSoftCACHE; //cache for value with same name

// #7
[Tooltip("Share of Yellow Star Soft prefabs in percentages.")]
[Range(0f, 100f)]
[SerializeField]
private float shareOfYellowStarSoft;
private float shareOfYellowStarSoftCACHE; //cache for value with same name

/* Controls sliders for stars shares in Unity Inspector. Doesn't work in actual game.*/
#if UNITY_EDITOR
private void OnValidate()
{
    ValidateStarsShares();

}

private void ValidateStarsShares() // Find which value the user changed, and update the rest from it.
{
    // Skip this if we haven't cached the values yet.
    if (shareOfBlueStarHardCACHE >= 0)
    {

        // Find which value the user changed, and update the rest from it.
        if (shareOfBlueStarHardCACHE != shareOfBlueStarHard) // #0 star share changed
        {
            DistributeProportionatelyForStars(ref shareOfBlueStarHard, ref shareOfBlueStarMedium, ref shareOfBlueStarSoft, ref shareOfRedStarSoft,
               ref shareOfWhiteStarHard, ref shareOfWhiteStarMedium, ref shareOfWhiteStarSoft, ref shareOfYellowStarSoft);
        }
        else if (shareOfBlueStarMediumCACHE != shareOfBlueStarMedium) // #1 star share changed
        {
            DistributeProportionatelyForStars(ref shareOfBlueStarMedium, ref shareOfBlueStarHard, ref shareOfBlueStarSoft, ref shareOfRedStarSoft,
               ref shareOfWhiteStarHard, ref shareOfWhiteStarMedium, ref shareOfWhiteStarSoft, ref shareOfYellowStarSoft);
        }
        else if (shareOfBlueStarSoftCACHE != shareOfBlueStarSoft) // #2 star share changed
        {
            DistributeProportionatelyForStars(ref shareOfBlueStarSoft, ref shareOfBlueStarHard, ref shareOfBlueStarMedium, ref shareOfRedStarSoft,
               ref shareOfWhiteStarHard, ref shareOfWhiteStarMedium, ref shareOfWhiteStarSoft, ref shareOfYellowStarSoft);
        }
        else if (shareOfRedStarSoftCACHE != shareOfRedStarSoft) // #3 star share changed
        {
            DistributeProportionatelyForStars(ref shareOfRedStarSoft, ref shareOfBlueStarHard, ref shareOfBlueStarMedium, ref shareOfBlueStarSoft,
               ref shareOfWhiteStarHard, ref shareOfWhiteStarMedium, ref shareOfWhiteStarSoft, ref shareOfYellowStarSoft);
        }
        else if (shareOfWhiteStarHardCACHE != shareOfWhiteStarHard) // #4 star share changed
        {
            DistributeProportionatelyForStars(ref shareOfWhiteStarHard, ref shareOfBlueStarHard, ref shareOfBlueStarMedium, ref shareOfBlueStarSoft,
               ref shareOfRedStarSoft, ref shareOfWhiteStarMedium, ref shareOfWhiteStarSoft, ref shareOfYellowStarSoft);
        }
        else if (shareOfWhiteStarMediumCACHE != shareOfWhiteStarMedium) // #5 star share changed
        {
            DistributeProportionatelyForStars(ref shareOfWhiteStarMedium, ref shareOfBlueStarHard, ref shareOfBlueStarMedium, ref shareOfBlueStarSoft,
               ref shareOfRedStarSoft, ref shareOfWhiteStarHard, ref shareOfWhiteStarSoft, ref shareOfYellowStarSoft);
        }
        else if (shareOfWhiteStarSoftCACHE != shareOfWhiteStarSoft) // #6 star share changed
        {
            DistributeProportionatelyForStars(ref shareOfWhiteStarSoft, ref shareOfBlueStarHard, ref shareOfBlueStarMedium, ref shareOfBlueStarSoft,
               ref shareOfRedStarSoft, ref shareOfWhiteStarHard, ref shareOfWhiteStarMedium, ref shareOfYellowStarSoft);
        }
        else if (shareOfYellowStarSoftCACHE != shareOfYellowStarSoft) // #7 star share changed
        {
            DistributeProportionatelyForStars(ref shareOfYellowStarSoft, ref shareOfBlueStarHard, ref shareOfBlueStarMedium, ref shareOfBlueStarSoft,
               ref shareOfRedStarSoft, ref shareOfWhiteStarHard, ref shareOfWhiteStarMedium, ref shareOfWhiteStarSoft);
        }
    }

    // Cache the old values for the next edit.
    shareOfBlueStarHardCACHE = shareOfBlueStarHard;
    shareOfBlueStarMediumCACHE = shareOfBlueStarMedium;
    shareOfBlueStarSoftCACHE = shareOfBlueStarSoft;
    shareOfRedStarSoftCACHE = shareOfRedStarSoft;
    shareOfWhiteStarHardCACHE = shareOfWhiteStarHard;
    shareOfWhiteStarMediumCACHE = shareOfWhiteStarMedium;
    shareOfWhiteStarSoftCACHE = shareOfWhiteStarSoft;
    shareOfYellowStarSoftCACHE = shareOfYellowStarSoft;
}

void DistributeProportionatelyForStars(ref float changed, ref float one, ref float two, ref float three,
    ref float four, ref float five, ref float six, ref float seven)
{
    changed = Mathf.Clamp(changed, 0.0f, TOTAL_STARS_SHARE);
    float total = TOTAL_STARS_SHARE - changed;

    float oldTotal = one + two + three + four + five + six + seven;

    if (oldTotal > 0)
    {
        float fraction = 1f / oldTotal;
        one = Mathf.RoundToInt(total * one * fraction);
        two = Mathf.RoundToInt(total * two * fraction);
        three = Mathf.RoundToInt(total * three * fraction);
        four = Mathf.RoundToInt(total * four * fraction);
        five = Mathf.RoundToInt(total * five * fraction);
        six = Mathf.RoundToInt(total * six * fraction);
        seven = Mathf.RoundToInt(total * seven * fraction);
    }
    else
    {
        one = two = three = four = five = six = seven = total / 7;
    }

    // Assign any rounding error to the last one, arbitrarily.
    // (Better rounding rules exist, so take this as an example only)
    //c += total - a - b - c;
}
#endif

```

# Answer
First, I'd make a struct to package together your prefabs and weights, so you can store them in an array without having to juggle so many named variables to figure out which number goes with which prefab.

```
[System.Serializable]
public struct PrefabEntry {
    #if UNITY_EDITOR
    // This helps it look neater in the inspector.
    [HideInInspector]
    public string name;
    #endif
    public GameObject prefab;
    public float weight;
}

```

Next we set aside an array of these to use in-game. We'll maintain the invariant that these weights always add to 100.

```
[SerializeField]
[HideInInspector]
PrefabEntry[] _normalizedPrefabs;

```

But we hide that version, and instead show an Inspector-only version to the user:

```
#if UNITY_EDITOR
[SerializeField]
PrefabEntry[] _weightedPrefabs = new PrefabEntry[0];

void OnValidate() {
    // When the array is modified,
    // update all the entries' names,
    // and total up the weight accounted for.
    float totalWeight = 0f;

    for(int i = 0; i < _weightedPrefabs.Length; i++) {
        var entry = _weightedPrefabs[i];
        if(entry.prefab == null)
            continue;

        entry.name = entry.prefab.name;
        _weightedPrefabs[i] = entry;
        totalWeight += entry.weight;
    }

    if (totalWeight == 0f)
        return;

    float reweight = 100f / totalWeight;

    // Create/resize the normalized version.
    if(_normalizedPrefabs == null || _normalizedPrefabs.Length != _weightedPrefabs.Length)
        _normalizedPrefabs = new PrefabEntry [_weightedPrefabs.Length];

    // Fill this array with copies of the original,
    // reweighted to add up to 100
    for(int i = 0; i < _weightedPrefabs.Length; i++) {
        var entry = _weightedPrefabs[i];
        if(entry.prefab == null)
            entry.weight = 0f;

        entry.weight *= reweight;
        _normalizedPrefabs[i] = entry;
    }
}
#endif

```

Now every time you make a change, we ensure the version used in-game is adjusted to add up to 100 *without changing the original values* shown in the inspector.

So if you want to make a coordinated change like setting four prefabs to 25% each and the rest to 0, you can do that in one fell swoop without fighting the renormalizing logic that keeps trying to change your zeroes to`1/remainingTotal` ;)

You'll just need to be careful that all your scripts that consume this data use the `_normalized` version. If you want to enforce that, you could encapsulate this in a type with a public getter for only the `_normalized` array.

Here's what it looks like in the Inspector:

One last note: usually for probability math, we'll normalize so the total is 1 instead of 100, but I've left it as 100 above to fit with what you're doing so far.
> 1 votes

---
Tags: unity, c#, procedural-generation, scripting, editors
---


# Question
Title: Assigning sprite to a sorting layer through scripting
I have few prefabs with sprites which I want to assign to different sorting layers. How can I do it? I am also wondering if sorting layers matter if I use a perspective camera. Do they?

# Answer
To change the sorting layer and/or the sorting order of a sprite, just use:

```
SpriteRenderer mySpriteRenderer = GetComponent<SpriteRenderer>();
mySpriteRenderer.sortingLayerName = "/*[Sorting Layer Name String]*/";
mySpriteRenderer.sortingOrder = /*[Sorting Order Number]*/;

```

Be aware that if you use a `string` different from any sorting layer that you have defined in the `Tags and Layers` window, Unity will set the layer to `Default`. I strongly suggest to use an `enum` in your code that will store all sorting layers names.

From code, you can access the array that contains all layers by using `SortingLayer.layers`

Regarding your other question, yes, sorting layer and order matter regardless of what type of camera you're using, but only relative to other sprite renderers.

This means that the rendering priority between a sprite and a 3D object will depend as usual from their respective distance from the camera, whereas the rendering priority among sprites will follow the same rules as the ones when using a 2D camera.
> 1 votes

---
Tags: unity, 2d, sprites, perspective, layers
---


# Question
Title: Why are the vertices from a mesh not transforming using a camera?
I am able to use a camera class to change the view and rotation of a simple quad, so I know it works, but when I move on to a more advanced geometry, such as a mesh, I am unable to affect the transform of the object at all. The WVP matrix does change in the mesh example (using print statements), but no movement or rotation is observed.

My camera first calls

```
camera.SetLens(0.33f * (float)Math.PI, Width / Height, 0.5f, 1000.0f)

```

on initialization, where width and height is the width and height of the window, SetLens is defined here:

```
public void SetLens(float fovY, float aspect, float zn, float zf)
{
  FovY = fovY;
  Aspect = aspect;
  NearZ = zn;
  FarZ = zf;

  NearWindowHeight = 2.0f * NearZ * (float)Math.Tan(0.5f * FovY);
  FarWindowHeight = 2.0f * FarZ * (float)Math.Tan(0.5f * FovY);

  Proj = Matrix.PerspectiveFovLH(FovY, Aspect, NearZ, FarZ);
}

```

Every frame I call Draw, and it updates the view matrix of the camera. (Draw is on the bottom of this code snippet)

```
public void UpdateViewMatrix()
{
  var r = Right;
  var u = Up;
  var l = Look;
  var p = Position;

  l = Vector3.Normalize(l);
  u = Vector3.Normalize(Vector3.Cross(l, r));

  r = Vector3.Cross(u, l);

  var x = -Vector3.Dot(p, r);
  var y = -Vector3.Dot(p, u);
  var z = -Vector3.Dot(p, l);

  Right = r;
  Up = u;
  Look = l;

  var v = new Matrix();
  v[0, 0] = Right.X;
  v[1, 0] = Right.Y;
  v[2, 0] = Right.Z;
  v[3, 0] = x;

  v[0, 1] = Up.X;
  v[1, 1] = Up.Y;
  v[2, 1] = Up.Z;
  v[3, 1] = y;

  v[0, 2] = Look.X;
  v[1, 2] = Look.Y;
  v[2, 2] = Look.Z;
  v[3, 2] = z;

  v[0, 3] = v[1, 3] = v[2, 3] = 0;
  v[3, 3] = 1;

  View = v;
}

private void Draw()
{
  camera.UpdateViewMatrix();
  Matrix view = camera.View;
  Matrix proj = camera.Proj;
  Matrix world = Matrix.Identity;
  Matrix WVP = world * view * proj;
  d3dDeviceContext.UpdateSubresource(ref WVP, worldViewProjectionBuffer);
  ...
 }

```

For the camera to make changes, I call the following functions on keypress/mouse movement

```
public void Strafe(float d)
{
  Position += Right * d;
}

public void Walk(float d)
{
  Position += Look * d;
}

public void Pitch(float angle)
{
  var r = Matrix.RotationAxis(Right, angle);
  Up = Vector3.TransformNormal(Up, r);
  Look = Vector3.TransformNormal(Look, r);
}

public void Yaw(float angle)
{
  var r = Matrix.RotationY(angle);
  Right = Vector3.TransformNormal(Right, r);
  Up = Vector3.TransformNormal(Up, r);
  Look = Vector3.TransformNormal(Look, r);
}

```

In my vertex shader I just set the position of the vertex like this:

```
output.position = mul(worldViewProj, position);

```

So again, I can get it working with a simple triangle or quad, but I need to load triangles and their connectivity from a TIN and I am able to draw the mesh on the screen but my camera operations are not translating the mesh at all. Any clues on what I might be doing wrong? For clarification, the whole mesh should be considered one object.

# Answer
First of all, I haven't looked through all that code, but my first guess would be this line in the shader:

```
output.position = mul(worldViewProj, position);

```

If your position.w is 0, then no translation (movement) from the camera will affect the output.position. Can you try to force set the w component to 1 like this:

```
output.position = mul(worldViewProj, float4(position.xyz, 1));

```

Otherwise, you may have to debug the cpu code. For GPU debugging, you can try graphics/GPU debugger tools, which can step through shader code like it was cpu code (but chances are that it won't work for your GPU).

Good Luck!
> 1 votes

---
Tags: directx, projection-matrix
---


# Question
Title: How to handle hitboxes/hurtboxes in animations?
I'm curious how I should go about structuring hitboxes and hurtboxes for my actors. For context, I'm developing a game engine in OpenGL, using C# and OpenTK. I have developed a working skeletal animation system, which loads animations using Assimp, and then passes BoneIDs, BoneWeights, and Transform matrices to the Vertex shader, which calculates all vertex deforms appropriately for the current animation keyframe (or current interpolation between keyframes).

Is there a set standard for calculating collision in animations? I'd prefer to continue using Assimp, which means using standard, recognizable animation formats that my engine can load in, so I'd rather not store any collision data in the animation files, unless there is a precedent for this or room for metadata or something.

My current thoughts: One option would be to calculate the hitboxes and hurtboxes upon loading an animation, and have a mapping that determines which meshes are hitboxes and which are hurtboxes. The second option would be to create a new file format where I store my hitboxes and hurtboxes in a way that is similar to animation files (minus bone weights, since I'll just be transforming the scale/position of axis-aligned rectangles), where I can determine keyframes for hitboxes and hurtboxes, then interpolate based off of these to get the current collision box for each frame. I could combine the two options by automatically generating these files from the animations, then editing them manually until they are reasonable.

Am I on the right track, or are there smarter ways of going about this? I don't want to reinvent the wheel if there are better options available.

# Answer
> 1 votes
> Is there a set standard for calculating collision in animations?

No, not really. It largely ends up depending on what you want out of the system.

I'd generally suggest you store the bounding information in the mesh, not the animation, and just weight the bounding primitives similarly to the way you weight the bones. This means the animation can be reused on similar characters of different girth (thicker arms, for example) more easily.

If you just want reasonably accurate, tight-fitting oriented boxes/capsules/rectangles around the actual limbs and body of the character, it's probably reasonable to compute those boxes by processing the bounds of all vertices affected by a given bone ID (that is, all the vertices weighted to the forearm bone are used to compute the bounding capsule of the forearm in the mesh).

However, it may ultimately be easier to just author the collision capsules directly into the mesh, tagged so you can process them appropriately during export/import. Authoring capsules in modelling tools is pretty easy, and this gives you the flexibility of making some special capsules that fit more loosely for special attacks, or the like.

Animations can include metadata for enabling or disabling particular collision capsules (or perhaps just specific collision responses) during the animation, if needed. You may need to export that as a sidecar file.

Basically, you're on a reasonable track. Both of your options are viable, although what I would prefer is probably closer to the second choice. And even if you do the first option you listed I'd recommend trying to do that computation when you *export* rather than when you load into the game, since it won't change between then and you'll save your users a bit of load time.

---
Tags: opengl, collision-detection, animation, skeletal-animation
---


# Question
Title: Generate random number biased to an input value
I've got enemies with a difficulty rating from 0 to 1. I want to generate a random reward that tends to increase as the difficulty rating rises, but still be possible to have a value anywhere in the range. Essentially, the average should increase with the difficulty, but maintain the full randomness range.

One attempt was to simply multiply a uniform random number by the difficulty, but this puts a cap on the output. What is the best approach to accomplish this?

# Answer
> 1 votes
Here's one simple method:

```
rarity = 1 - Pow(random(), 1 + difficultyRating * maxBias)

```

Here `maxBias` is a positive value that lets you control how skewed you want your probabilities to get.

The higher difficultyRating gets, the more of the probability space gets devoted to the top end of the rarity scale.

---
Tags: mathematics, algorithm, distribution, probability
---


# Question
Title: How To Resize Existing Texture In OpenGL 4.3
I would like to know how to resize an existing **OpenGL 4.3** texture while keeping the current contents. i'm using `glTexImage2D()`. Do I simply re-call `glTexImage2D()` with `nullptr` for the `data` paramater?

# Answer
> 2 votes
You cannot.

You can create a new texture and copy the contents of the pixel data from the old texture into the appropriate place of the new one. But `glTexImage` will reallocate the storage for the texture. And not like `realloc` does; it works like `malloc` followed by `free`ing the old memory.

Its best to avoid this problem by making the texture as large as you will reasonably need it to be, then living within that storage.

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


title: How are the scripts connecting?

text:
# Question
Title: How are the scripts connecting?
I been following the playlist in brackeys for unity for beginners and it gets a little fast and complicated at the end and just curious about if a script makes a reference like:

```
FindObjectOfType<GameManager>().EndGame();

```

With GameManager being a empty and EndGame being a function to another script.

It runs it but does it connect to the script through the GameManager object since it's connected to the script?

I just want to know how it's getting to the script function and that is the only mention of GameManager in the whole script.

# Answer
**Why is this happening?**

Unity's "FindObjectOfType()" function looks through the **entire hierarchy** (not just the object the script is on) for the first active instance of a game object with the type specified. More info can be found in the official documentation.

If you look in your hierarchy under the "LevelOne" scene you can see that you have your GameManager object active in the list. So when your player script calls this "FindObjectOfType()" function Unity is returning the first item in its hierarchy which matches your request. Then you call "EndGame()" on this returned object.

**What does FindObjectOfType return?**

In response to your question on @LinkWindcrafter's answer: An "Object" and a "GameObject" are two separate things. Each item in your hierarchy is an individual GameObject. Each GameObject has a list of components which you can view and edit in the inspector after selecting a GameObject. Components and GameObjects both derive from Unity's base class Object.

Object \> GameObject

and

Object \> Component \> Behavior \> MonoBehavior \> Your GameManager

In short:

```
FindObjectOfType<GameManager>()

```

returns an Object cast as a GameManager type, and then you call it's "EndGame()" function on it. The specific object being returned is the first instance of your script that Unity can find in your scene hierarchy.

Using the Component property "gameobject" you can retrieve the GameObject it is attached to if you wish:

```
GameObject go = self.gameobject;

```

**Potential Problems**

As the documentation mentions this function is very slow. It loops through every active game object in your entire scene and does a check to see if it's what your looking for. The bigger your scenes get the longer this function will take. I typically see it used in initialization where you can afford to do inefficient calls rather than update where you want to trim down your processing times.

The documentation also mentions that it returns the first active object matched. So if the object is turned off, or there is a second one which matches your request you may get the wrong object (or null if there isn't one) which could either crash your game, or cause unexpected results.

This next problem is more nit picky than actually discussing functionality. As you've already encountered this function isn't the most readable. It's a borderline global call and it makes it difficult to know not only which object is being used, but also which object was intended to be used.

**Solutions**

I can see in the pictures you've posted that your familiar with setting up scripting variables that you can alter from within the editor. If you add either a public, or (better) a \[SerializeField\] GameManager variable to the script your calling it from you can assign it in the editor by dragging and dropping the instance you want to use. This will let whoever is looking at your script know exactly which object you want to call "EndGame()" on, and it will avoid the issue of calling the slow "FindObjectOfType()" function.
> 1 votes

# Answer
What that line does is that it fetches for a UnityEngine's Object on the scene with the type defined on the angle brackets, it returns that script, or null if there wasn't one.

The way script references work on Unity is that the script fetched needs to be attached to a GameObject, **FindObjectOfType** searches if GameObjects on the scene have that script attached.

That is the reason it makes that function call once, otherwise it would have stored it on a variable of that type. Like this:

```
public class Example : MonoBehaviour
{
    private GameManager manager;
    public bool condition;

    void Start()
    {
        manager = FindObjectOfType<GameManager>() as GameManager;
    }

    Update()
    {
        if(condition) manager.EndGame();
    }
}

```

See the **method's documentation** for reference.
> -1 votes

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


title: efficient way of matching coordinates

text:
# Question
Title: efficient way of matching coordinates
I have 2 lists of coordinates in C# one as of coordinates of Drivers and the other as of coordinates of cafes. I am looking for an efficient way of populating a static Dictionary with its key as of a Driver from the first list and its associated values of all Cafes in 500 meters radius. Number of cafes can be up to 100000 and number of Drivers are dynamic from 1 to 100000

```
public void ManageList() {
GlobalList.Clear();
foreach (var driver in driverList)
    {
        var driverCoords = new GeoCoordinate(driver.Latitude, driver.Longitude);
        List<Cafe> matchedCafes = new List<Cafe>();

        foreach (var cafe in cafeList)
        {
            var cafeCoords = new GeoCoordinate(cafe.Latitude, cafe.Longitude);

            if (cafeCoords.GetDistanceTo(driverCoords) <= 500) {
                matchedCafes.Add(cafeCoords);
            }
        }

        GlobalList.Add(driverCoords, matchedCafes);
    }
}

```

the above works fine as long as drivers are not movable objects. If I want to send the driver's coordinates every 5 seconds and update the GlobalList per driver the above algorithm fails as I am basically clearing the whole list and populate it again.

# Answer
The algorithm can be optimized by including a broad phase, this uses a less complicated algorithm and it narrows down the possible candidates as much as possible.

In this case I would use an AABB square with a side length of 1000 units, this contains the circle completely.

This works fine until you get to the 100000 cafes and 100000 drivers scenario. I don't think there's an efficient enough algorithm to handle that, but there are definitely better solutions, than simply brute-forcing your way through the cafes for every driver.

Try dividing the world into squares, possibly 500 by 500 squares and place the cafes into these based on their locations. When you need to find the cafes closer, than 500 metres, you first need to get the square the driver is in (this can be done with a simple `(floar(x/500), floar(y/500))`, where x and y are the driver's position and the resulting pair is the position of the square, then only check the cafes in that square and the 8 neighbouring ones.
> 0 votes

---
Tags: geolocation
---


# Question
Title: How do you rotate RigidBody2D along a given access using velocity and not transform?
I am trying to rotate my player along the centre of the world in Unity3D. All the tutorials and references I have looked through till now have left me to this working code:

```
void MoveAlongCurve(bool moveClockwise) {
    if (!moveClockwise)
        timeCounter += moveSpeed*Time.fixedDeltaTime;
    else
        timeCounter -= moveSpeed*Time.fixedDeltaTime;

    float x = Mathf.Cos (timeCounter);
    float y = Mathf.Sin (timeCounter);

    transform.position = new Vector3 (distFromCentre*x, distFromCentre*y,0);
}

```

Also this seems to work fine as well:

```
transform.RotateAround (Vector3.zero,new Vector3(0,0,1),speed);

```

Now my question is how do i move my player using velocity? I was forced to keep my body as '**kinematic rigidbody2D**' however I want my player to be a '**dynamic rigidbody2D**'.

My reason for this is several: 1. Movement via velocity makes it independent of the timeCounter. 2. Dynamic Bodies enable collisionDetection. Hence it is basically a requirement for my game.

Thank you so much for taking the time to read this! Any suggestions or nudges in the right direction would be greatly appreciated and if you find anything wrong in my code or approach please comment!

# Answer
You can transform any arbitrary position change into a velocity:

```
Vector2 VelocityToReach(Vector2 destination) {
    Vector2 displacement = destination - body.position;
    return displacement/Time.fixedDeltaTime;
}

```
> 0 votes

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


# Question
Title: Problems applying movement to a RigidBody in Unity
I'm working on a driving game, and I've been using RigidBody.MovePosition (non-kinematic) to move the car. I've read that this is not the best method for physics reasons, but I've had massive problems moving objects around with the other techniques. So far, it's been working out great, at least with horizontal movement.

However, now I'm trying to turn the car into a hover-car, and it seems MovePosition is terrible with vertical movement. Rather than trying to fight what is likely a losing battle, I'd like to get either AddForce or velocity working. I'm only concerned with the horizontal (for now).

Here are the three versions, along with the results I'm getting.

**RigidBody.MovePosition:**

Works great, at least for forward movement. Attempting the same technique with Vector3.up results in all kinds of broken and unpredictable behavior with collisions and physics, though.

```
  void Start ()
    {
    body = GetComponent<Rigidbody> ();

    forward_speed = 0f;
    forward_max_speed = .9f;
    forward_acceleration = .02f;
    forward_movement = Vector3.zero;
    rotation_multiplier = 2.5f;
    }

  //////////////////////////////////////////////////

  void FixedUpdate ()
    {
    if (key_up)
      {
      if (forward_speed < forward_max_speed) forward_speed += forward_acceleration;
      }
    else if (key_down)
      {
      if (forward_speed > -forward_max_speed) forward_speed -= forward_acceleration;
      }
    else
      {
      if (forward_speed > -.1f && forward_speed < .1f) forward_speed = 0f;
      if (forward_speed != 0f) forward_speed = forward_speed * 0.9f;
      }

    if (key_left) turning_rotation = forward_speed * -rotation_multiplier;
    if (key_right) turning_rotation = forward_speed * rotation_multiplier;

    // rotation
    transform.Rotate (0f, turning_rotation, 0f);

    // forward
    forward_movement = transform.forward * forward_speed;
    body.MovePosition (body.position + forward_movement);
    }

```

**RigidBody.velocity:**

The car performs great on flat surfaces, but if it goes airborne for any reason, it falls incredibly slowly, basically letting the player fly around (but not the way I intended). Freezing X and Z rotations partially mitigates the flying, but doesn't fix the slow falling, and also causes the car to have strangely intense trouble getting up inclines. I can't fathom why assigning the velocity would mess with gravity. Unity, you've outdone yourself.

```
  void Start ()
    {
    body = GetComponent<Rigidbody> ();

    forward_speed = 0f;
    forward_max_speed = 50f;
    forward_acceleration = 1f;
    forward_movement = Vector3.zero;
    rotation_multiplier = .067f;
    }

  //////////////////////////////////////////////////

  void FixedUpdate ()
    {
    if (key_up)
      {
      if (forward_speed < forward_max_speed) forward_speed += forward_acceleration;
      }
    else if (key_down)
      {
      if (forward_speed > -forward_max_speed) forward_speed -= forward_acceleration;
      }
    else
      {
      if (forward_speed > -.1f && forward_speed < .1f) forward_speed = 0f;
      if (forward_speed != 0f) forward_speed = forward_speed * 0.9f;
      }

    if (key_left) turning_rotation = forward_speed * -rotation_multiplier;
    if (key_right) turning_rotation = forward_speed * rotation_multiplier;

    // rotation
    transform.Rotate (0f, turning_rotation, 0f);

    // forward
    body.velocity = transform.forward * forward_speed;
    }

```

**RigidBody.AddForce:**

This one *almost* works, but the car slides around like it's Disney on ice. Fun, but not right. After changing direction, it seems to take a half second for the car's movement or the force direction to catch up with the rotation, so it slides to the side pretty badly. The same thing happens with gas and brakes. There's a noticeable and frustrating delay. I also had the same problem when I tried vertical movement with this - it just refuses to stop at the elevation I tell it to. I've tried all four of the different ForceMode settings, and aside from having to massively adjust the forward\_max\_speed and forward\_acceleration values, they feel mostly the same. AddForce is the same method used in the CharacterFirstPerson scene in the Standard Assets Project, but I noticed the exact same control delay in that project as well. The guy doesn't start and stop on a dime.

```
  void Start ()
    {
    body = GetComponent<Rigidbody> ();

    forward_speed = 0f;
    forward_max_speed = 70f;
    forward_acceleration = 5f;
    forward_movement = Vector3.zero;
    rotation_multiplier = .02f;
    }

  //////////////////////////////////////////////////

  void FixedUpdate ()
    {
    if (key_up)
      {
      if (forward_speed < forward_max_speed) forward_speed += forward_acceleration;
      }
    else if (key_down)
      {
      if (forward_speed > -forward_max_speed) forward_speed -= forward_acceleration;
      }
    else
      {
      if (forward_speed > -.1f && forward_speed < .1f) forward_speed = 0f;
      if (forward_speed != 0f) forward_speed = forward_speed * 0.9f;
      }

    if (key_left) turning_rotation = forward_speed * -rotation_multiplier;
    if (key_right) turning_rotation = forward_speed * rotation_multiplier;

    // rotation
    transform.Rotate (0f, turning_rotation, 0f);

    // forward
    forward_movement = transform.forward * forward_speed;
    body.AddForce (forward_movement, ForceMode.Acceleration);
    }

```

What I'd like to do is get either the RigidBody.AddForce or RigidBody.velocity method working properly so everything is on the up and up with the physics engine. Unfortunately, I've run out of ideas and I'm too frustrated with Unity right now to see the problem clearly.

# Answer
> 0 votes
Based partly on Robin van Ee's answer, I was able to fix movement on both AddForce and velocity, and get them working "properly" (according to me, at least).

It seems that when Unity applies force or velocity, that force doesn't stay local to the direction the object is travelling, and instead gets converted to a global force. When the object changes direction, the force (or velocity) doesn't change direction with it, and the physics engine take a few seconds to interpolate between the old force and the new force. Meanwhile, your plane/boat/dog/unicycle has left the map sideways.

Here's what I did.

**AddRelativeForce Method:**

I'm not sure if it matters that I switched from AddForce to AddRelativeForce, but it does save me having to transform the local vector to the world vector. The big change was stopping the undesired x-axis movement. I'm constantly checking for force on the x-axis and applying an equal and opposite force to cancel it out. I also had to do a similar compensation for forward / back movement, since Unity's arbitrary interpolation was messing up my desired acceleration and deceleration. This seems a bit hacky, and I still think there *ought* to be a more straight-forward (pun intended) way of applying force that stays local and changes instantly, but this works for now.

```
  Mathf.Clamp (forward_speed, -forward_max_speed, forward_max_speed);
  float forward_speed_adjustment = forward_speed - transform.InverseTransformDirection (body.velocity).z;
  float side_speed_adjustment = -transform.InverseTransformDirection (body.velocity).x;
  body.AddRelativeForce (side_speed_adjustment, 0f, forward_speed + forward_speed_adjustment, ForceMode.VelocityChange);

```

**Velocity Method:**

The mistake I was making here was trying to set velocity directly, which was overwriting *all* movement, including the vertical movement as caused by gravity. I also had to stop the x-axis movement, which was much easier here.

```
  Mathf.Clamp (forward_speed, -forward_max_speed, forward_max_speed);
  Vector3 current_velocity_vector = transform.InverseTransformDirection (body.velocity);
  current_velocity_vector.z = forward_speed;
  current_velocity_vector.x = 0f;
  body.velocity = transform.TransformDirection (current_velocity_vector);

```

With both methods, the car now feels exactly like it did under MovePosition, I've got complete control over the car's motion, and the movement code is (theoretically) completely physics-friendly.

# Answer
> 2 votes
Rigidbody.MovePosition does the same as setting transform.position, but calculates collision along the way.

Rigidbody.velocity is the distance and direction the Rigidbody travels each second, including all external forces. So setting this directly will indeed disable gravity.

Rigidbody.AddForce is what you need, but vehicle physics aren't as simple as you think. You will want to check if the wheels are grounded, you can do this by adding Raycasts where the wheels are. Then you use RigidBody.AddRelativeForce to move the car forward, and AddRelativeTorque for steering. You can stabilize the car using this:

```
rigidbody.AddRelativeForce(Vector3.left * localVelocity.x, ForceMode.VelocityChange);

```

This will cancel out *all* horizontal movement. If you want the car to drift a little, you could change it like this:

```
float drift = 1.2f;
rigidbody.AddRelativeForce(Vector3.left * localVelocity.x / drift, ForceMode.VelocityChange);

```

But what I can recommend most is watching this video on raycast vehicles. It has a very good explanation on developing simple vehicles that feel good to drive.

# Answer
> 0 votes
For a car simulation, generally AddForce is the recommended method.

To solve the sliding issue, take a look at the physics materials. There, you will find an option to adjust friction.

Documentation for physics materials: https://docs.unity3d.com/Manual/class-PhysicMaterial.html

---
Tags: unity, physics, movement, rigidbody
---


title: Unity wheel collider extra camber angle

text:
# Question
Title: Unity wheel collider extra camber angle
I want to give the value of a camber to the wheel collider my game. When the car stops, there is no problem visually, but as the wheel rotates, the wheel makes odd rotational movements together with the value of camber.

```
foreach (var axle in axles){
    Vector3 pos;
    Quaternion rot;
    axle.wheel.GetWorldPose(out pos, out rot);
    axle.tire.position = pos;
    axle.tire.Rotate(axle.wheel.rpm / 60 * 360 * Time.deltaTime, 0, (camperValue * camperFactor));
    axle.tire.localEulerAngles = new Vector3(
         axle.tire.localEulerAngles.x,
         axle.wheel.steerAngle - axle.tire.localEulerAngles.z,
         axle.tire.localEulerAngles.z);

    axle.wheel.motorTorque = 300 * Input.GetAxis("Vertical");
    if (axle.index < 2)
        axle.wheel.steerAngle = 30 * Input.GetAxis("Horizontal");

    axle.wheel.brakeTorque = 1000 * (Input.GetKey(KeyCode.Space) ? 1 : 0);
}

```

# Answer
> 1 votes
`axle.tire.Rotate` means that you add rotation every frame, so you're constantly adding castor value, making wheel rotate.

What you want is to set camber rotation:

```
axle.tire.rotation = rot * Quaternion.Euler(camberAxle * camber)

```

(Swap them if you got weird results.) `camberAxle` is wheel forward direction which is usually car forward direction plus wheel `steerAngle` (around `steerAxis`, which is usually `carTransform.Up`):

```
camberAxle = Quaternion.Euler(carTransform.up * steerAngle) * carTransform.forward;

```

---
Tags: unity, physics, vector, quaternion
---


title: How can i achieve an outline effect?

text:
# Question
Title: How can i achieve an outline effect?
I have a small shader that does the following things:

(First cgprogram block)

1. Copy the current mesh and scales it along the normals
2. Assign a color to the inflated mesh
3. Draw the inflated mesh

(Second cgprogram block)

1. Assign a color to the original mesh
2. Draw the original mesh

In-game you can only see the inflated mesh because the smaller one gets inglobated.

Is there a way to re-order the rendering order, by drawing first the inflated mesh and then the original mesh, resulting in a sort of outline effect?

**What I tried**

1. Setting *Cull Front* on the inflated mesh and *Cull Back* on the original mesh

I copied this approach from an outline shader. Unfortunately it leads to other problems such as bad intersecting between inflated mesh in-game.
2. Changing the *Queue* in the shader between the two CGPROGRAM blocks

I set the first CGPROGRAM block on `"Queue" = "Geometry-10"` and the second on `"Queue" = "Geometry+0"` but.. no effect.

Is there a way to obtain the desired effect? Thanks in advance.

Here are some images to make the question a bit clearer:

**Current wireframe situation**

Original mesh inside, inflated mesh outside

**Current shaded situation**

**Desired outcome**

**Inflated mesh set on Cull Front**

This is the aforementioned problems between intersecting meshes. The inflated meshes have z-fighting going on.

# Answer
> 1 votes
Your problem here isn't rendering order. Since your regular colour mesh pass is second, it will come after the outline blob.

But, if your outline blob is writing to the z-buffer, then every fragment of your regular mesh will fail the depth test, because there's some part of the outline blob sitting between it and the camera.

You can turn off depth writes for the outline pass with

```
ZWrite Off

```

in the same section where you do your culling settings. This will prevent the blob from writing to the depth buffer, so by the time the regular mesh draws the depth buffer will still be in the state it was in before you even started drawing this material & mesh.

Note though that this will increase overdraw. In the typical case, we draw the outline inside-out, second, so that it's the outline mesh that fails the depth test and is discarded, and we only need to blend the smaller region of pixels making up the outline. By rendering the blob first, every pixel on the interior of the model is going to get written into at least twice, and more if the model has concave shapes. For just this one effect it won't be a big cost, but watch out for using this "painter's algorithm" for lots of effects all over your game.

---
Tags: unity, shaders
---


# Question
Title: How do you call a program used to design a level from sprites?
How do you call the concept or the process of designing sprites in 2d graphics program, assembling them in that program and exporting them for your game?

I need that kind of program but I can't think of the correct terminology to search for it.

# Answer
It sounds like what are looking for is a *level editor* (or *map editor*). There are various kinds of level editing tools; we often qualify them by the type of data they edit.

For example you’re probably looking for (based on some info that was edited out of the question) a *tile-based* or *tile map* editor such as Tiled.

Also note that you don't *need* a level editor, necessarily. Plenty of people make tile-based games just using text editors to define the level data (using characters: `#` represents a wall, `.` a floor, `S` a character spawn, or whatever).
> 1 votes

---
Tags: sprites, terminology
---


# Question
Title: How to create a bounding box around a Sprite in C++?
Hello everyone, I am trying to create a bounding box around a Sprite in my simple Pong game. The bounding box needs to be a simple rectangle around the sprite so that it can act as a collision detector between the ball and paddle.

I have already tried to create the bounding box but it's not quite working as expected.

```
    float current_x = paddle_right->xPos();
    float current_y = paddle_right->yPos();
    float current_x2 = paddle_left->xPos();
    float current_y2 = paddle_left->yPos();

    float width_x = current_x + 16;
    float width_y = current_y + 150;
    float width_x2 = current_x2 + 16;
    float width_y2 = current_y2 + 150;

    if((x_pos > current_x && x_pos < width_x && y_pos > current_y && y_pos < width_y)||
        (x_pos > current_x2 && x_pos < width_x2 && y_pos > current_y2 && y_pos < width_y2))
    {
        dir_vector.setX(dir_vector.getX() * -1);
    }

```

The above code is the code I have used to create said bounding box, but like I said, it's simply not working correctly (As in the ball will sometimes go through the Sprite or have an abnormal reaction to it such as bouncing the wrong way).

I hope I have explained this well, if not please ask me which part to explain again. Basically, I just want do create a bounding box around a Sprite (in this case, the Paddle) to which then the ball can collide from.

For reference I am using the AwesomeSauce Game Engine.

# Answer
Couple of things stand out.

Firstly i'm assuming a bunch of things just by your variable names. Here goes..

if your pong ball travels faster than 16 pixels per update then there is a chance that the ball can pass through the bat. You could verify this by limiting the ball speed.

On collision, it looks like you invert the x component of the ball direction vector. As the collision occurred inside the bat then even after you invert the direction the ball could still end up inside the bat after it is updated if its speed is low enough. To verify you could move the ball outside the bat in the direction it will travel. So if the new ball x direction is positive then place the ball on the right side of the bat. If new direction is negative place the ball on the left side of the bat.
> 1 votes

# Answer
> For reference I am using the AwesomeSauce Game Engine.

First is there a particular reason why you aren't using the primitives for a square in that engine? They've undoubtedly solved this problem for you.

It looks like you check if the ball position is within the bounds of either right or left paddle, then reverse the x direction of travel if it hits. With paddles of such small width, you have the potential that the ball will be fast enough that it passes through the paddle (causing it to miss).

Alternatively, if your ball is moving just right, you ball could jump into the paddle upon next movement, you would evaluate the ball colliding on the next check, the ball x reverses like normal, but on the following check the ball might still be inside and it would reverse directions again.

To solve these issues you need to take into account these edge cases:

1. you can make sure you evaluate the position of the ball before evaluating the change and direction (and immediately change the position again to reflect a collision). The ball will never be stuck inside the paddle this way and bounce out the wrong direction. This will not solve collision phasing however.
2. To solve the no collision on impact issue, you need to see if the line segment between your starting and final position of the ball intersected with the paddle then change direction.

Evaluating line-segment intersection in both scenarios will also work. You have to evaluate the balls possible next position in both before you figure out the true final position however.
> 0 votes

---
Tags: c++, sprites, bounding-boxes
---


# Question
Title: Why do I get errors cs1502 and cs1503 in my Destroy object script?
I have a script that lets the player place blocks (like in Minecraft), but I also want to be able to destroy those blocks. I keep getting error messages cs1502 and cs1503.

Could anyone take a look at the script and tell me what is wrong?

```
using UnityEngine;
using System.Collections;

public class TestForCube : MonoBehaviour {

  Ray ray;
  RaycastHit hit;

  // Use this for initialization
  void Start () {
  }

  // Update is called once per frame
  void Update () {

    ray = Camera.main.ScreenPointToRay (Input.mousePosition);

    if (Physics.Raycast (ray, out hit)) {

      if (Input.GetKeyDown (KeyCode.Mouse0)) {

        Vector3 position = hit.transform.position + hit.normal ;
        Quaternion rotation =  Quaternion.FromToRotation( Vector3.up , hit.normal );
        GameObject Placement = GameObject.CreatePrimitive( PrimitiveType.Cube );
        Placement.transform.position = position;
        Placement.transform.rotation = rotation;
      }

      {
        if (Physics.Raycast (ray, out hit)) {
          if (Input.GetKeyDown (KeyCode.Mouse1)) {
            DestroyObject( PrimitiveType.Cube);
          }
        }
      }
    }
  }
}

```

# Answer
The line that's giving you the errors is this:

```
DestroyObject(PrimitiveType.Cube);

```

The `DestroyObject` method requires an `Object` type parameter, but you're passing a `UnityEngine.PrimitiveType` `enum` type.

It's not completely clear what you want to achieve, but if you want to destroy a game object when it's clicked with the right mouse button, you should keep the references to the game objects you create when clicking the left mouse button and use `Destroy` instead of `DestroyObject`.
> 2 votes

---
Tags: unity
---


title: Build Placement and Connectors

text:
# Question
Title: Build Placement and Connectors
I'm having trouble with the logic for this problem. I've got a grid of modules. Each module may take 1 or more cells on the grid, and each cell of a module may have 1 or more connectors. The connectors are represented by an enum (or int). Adjacent modules may only be placed if they have matching connectors.

So, for example:

-Module A in position (0, 1) has a down (3) connector. -Module B in position (0, 2) has an up (1) connector.

This is a valid configuration.

-Module A in position (0, 1) has a down (3) connector. -Module B in position (0, 2) has an right (2) connector.

This configuration is invalid.

I've attached an image below for clarity:

# Answer
> 1 votes
The logic is quite simple:

```
goodToPlace = true
for every side
  if hasConnector(on that side) then
    if hasObject in direction of that side
      if not object.hasConnector(side - 2) then // side - 2 means to take opposite side
        goodToPlace = false

```

---
Tags: tiles
---


# Question
Title: Is there a way to make a game object invisible to only certain players?
I have found a few posts and blogs here and there. But all of the solutions they provide seem to be global.

Is there a way for let's say a multiplayer scenario where maybe an enemy has a cloaking device. Player 1 can't see said enemy but because Player 2 has thermo-goggles he can see the enemy just fine.

Is there an example of that scenario somewhere? I assume that it would have to be done at the camera level instead of the object instantiation. Maybe a state machine to designate these objects are invisible and one on the camera to state that you can see said invisible objects?

# Answer
You can specify layers that a camera should and should not render: https://docs.unity3d.com/Manual/Layers.html. Anything that should be rendered by one camera but not the other should be assigned to a different layer. You can do this through code by changing the `gameObject.layer`. Then, in a camera's Inspector, deselect that layer from the "Culling Mask" drop-down to make that layer invisible to that camera.

If the goggles are temporary, when you want to activate the goggles, modify the player camera's culling mask from code. Each bit in the culling mask is a one if that layer should be visible. So if you are revealing the nth layer, toggle the nth bit by XORing it with a mask:

```
cam.cullingMask = cam.cullingMask ^ (1 << n);

```

When the goggles are removed, do the same XORing to toggle it again, making the layer invisible again.
> 4 votes

---
Tags: unity, camera, multiplayer, gameobject
---


title: Attack Collision

text:
# Question
Title: Attack Collision
I'm very new to game development and have been learning more and more about collision detection and such.

However, I don't exactly understand how to detect that a player has attacked an enemy first or vice versa.

The attack would be a melee attack from one entity onto another.

Any general ideas would help :) thanks!

# Answer
The first thing to check would be if Player is attacking and Enemy is not attacking, it's simple enough, if there is a collision, it's the Player who is attacking.

Now if *both* are attacking, and if their attack motions take the same time, the one who started the attack first would be the one who "wins", i.e. the one who is tagged as attacking.

And if their attack motions do not take the same time, you could check who's closer to the end, percentage-wise, and tag that entity as the one performing the attack.

That being said, there is nothing preventing you to consider *both* as attacking if they're in an attack motion.

Another thing to consider: what part of an entity hit what part of the other entity? An axe could be split into two parts: *the blade* (the part that actually performs the attack) and *the rest*. If the player's blade is in an attack motion, and it hits an enemy's axe (which is also in an attack motion) on "the rest" part, then the enemy attacked too fast or not fast enough, while the player found a sweet spot: the player is tagged as attacking.
> 1 votes

# Answer
I pulled my attacks out as their own objects and made my characters attackables. When an attack is active and moving through space, it checks if it has collided with any attackables. When it does, it deals damage.
> 0 votes

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


# Question
Title: GLSL - multiplying fragment output color by normal after calling texture function displays wrong texture
So I'm quite new to OpenGL/GLSL. I'm trying to make multitexturing and simple normal lighting work. Here is a Vertex shader:

```
#version 130

uniform mat4 transform;

in vec3 vertPos;
in vec2 texUV;
in vec3 vertNorm;
in uint thisLayer;

out vec2 fragTexCoord;
out vec3 fragNorm;
out float fragLayer;

void main()
{
    gl_Position = transform * vec4(vertPos, 1.0f);

    fragTexCoord = texUV;
    fragLayer = float(thisLayer);
    fragNorm = vertNorm;
}

```

... and here is Fragment shader:

```
#version 130

uniform sampler2DArray texArray;
uniform uint texCount;
uniform float rTime;

in vec2 fragTexCoord;
in vec3 fragNorm;
in float fragLayer;

out vec4 color;

void main()
{
    float actual_layer = max(0, min(texCount - uint(1), floor(fragLayer + 0.5))); // Getting texture layer
    vec3 texCoord = vec3(fragTexCoord, actual_layer);

    color = texture(texArray, texCoord);
}

```

And it works fine:

Multiplying color.rbg by any constant works as expected:

```
color = texture(texArray, texCoord);
color.rgb *= vec3(0.5, 0.5, 0.5);

```

But if I try to multiply color.rgb by a normal, like this:

```
vec3 finalNorm = (normalize(fragNorm) + vec3(1,1,1))/vec3(2,2,2);
color = texture(texArray, texCoord);
color.rgb *= finalNorm;

```

The wall texture changes to the last texture in the array (the one on the top):

I have no idea why this happens. I normalize vertex normals and map their values into \[0, 1\] range, so colors will stay in \[0, 1\] range after multiplication as well. It is supposed to simply shift the colors intensity, like it did while multiplying by a constant, not change the texture itself, right? I am aware of the fact that this is not how you perform normal lighting, however, this is not the correct behavior as well, and I'm ripping my hair off as to why. Any help is appreciated. I will provide more info if needed.

EDIT: OS is Windows 10. GPU's: Intel HD 4600/Nvidia GTX 860M (happens on both of them). OpenGL version 4.3.0 build 20.19.15.4624.

Some additional info:

I use SOIL library to load data from PNG files. I use:

```
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, img_width, img_height, layer_count * 2, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);

```

to create a container for texture array, and use:

```
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, i, img_width, img_height, layer_count, GL_RGBA, GL_UNSIGNED_BYTE, data);

```

to load data into it. One issue I have with this is that glTexImage3D takes layer\_count (the number of textures) multiplied by 2, and I have no idea why as well! Maybe this is somehow related to the issue I'm having above?

# Answer
We need information on OS, GPU, drivers and opengl version you are using.

This appears like it may be the result of optimization after undefined behavior. To debug try the following:

```
#version 130

uniform sampler2DArray texArray;
uniform uint texCount;
uniform float rTime;

in vec2 fragTexCoord;
in vec3 fragNorm;
in float fragLayer;

out vec4 color;

void main()
{
    float actual_layer = max(0, min(texCount - uint(1), floor(fragLayer + 0.5))); // Getting texture layer
    vec3 texCoord = vec3(fragTexCoord, actual_layer);

    vec3 finalNorm = (normalize(fragNorm) + vec3(1,1,1))/vec3(2,2,2);
    color = texture(texArray, texCoord);
    color.rgb *= finalNorm;

}

```

Make sure this is the exact information for you fragment shader and make sure what you posted is the exact text for your vertex shader. If either of these aren't true, copy and paste the code and now try again to see if you have the same issue.

Next, you aren't calculating the normal correct, if you have the correct vertex normals in the first place, there is no need to A: normalize, they should already be normalized, and B: multiply and divide by a similar vector. I see you are trying to change the range of the normal from -1 +1 to 0, 1 with this.

First, make sure your normals are pre-normalized already. Next make sure they are correct, 0,0,0 is not a valid value for a normal, as the normalization for this may be undefined depending on your opengl spec, which can cause erratic behavior in your program from glsl compiler assumptions.

Next change your normal calculation to be the following:

```
vec3 finalNorm = (normalize(fragNorm) + 1.0)/2.0;

```

adding a scalar will add to all values of a vector, division by scalar will divide all values in the vector. normalization of something that is already normalized should not be an issue.

if things still haven't been sorted out, try manually multiplying color.rgb by an incorrect value (via forcing incorrect values on your vertex attributes)

```
color.rgb *= 1.0/0.0;

```

if you still see the same behavior you know there is some bad numeric value propagation happening. The above should appear as all white (except background).

```
color.rgb *= -1.0/0.0;

```

The above should appear as all black (except background).

```
color.rgb *= 0.0;

```

The above should be all black as well (except background).

Some more sanity checks, stop using uint values you may incidentally be causing undefined behavior in an un-obvious way. Try the following

```
float actual_layer = max(0, min(texCount - 1, floor(fragLayer + 0.5)));

```

You may also benefit from moving your camera positioning in relation to your object, seeing if you see any additional artifacts as hints.

Finally try changing the version on your shader to a more modern version of GLSL, such as `#version 330` if you are using opengl 3.3 and above.

If none of these things helped, you are either on a system with actual driver bugs, in which case update your drivers/change system. If it still has issues you more than likely have an issue in your code base that we can't help you with because you aren't showing us what you are doing out side of your shaders.
> 1 votes

---
Tags: opengl, glsl
---


# Question
Title: Error CS0029: Cannot implicitly convert type 'Fruits[]' to 'Fruits' (CS0029) (Assembly-CSharp)
I'm having an error produced when I compile my Unity game:

> Error CS0029: Cannot implicitly convert type 'Fruits\[\]' to 'Fruits' (CS0029) (Assembly-CSharp)

It's coming from the line:

```
f = Instantiate (fruitPrefab).GetComponents<Fruits>();

```

Why do I have this error and how can I resolve it?

Here is the rest of the code:

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

public class GameManager : MonoBehaviour {
  private const float REQUIED_SLICEFORCE=400.0f;
  private List<Fruits> fruties = new List<Fruits> ();
  public GameObject fruitPrefab;
  private float lastSpawn;
  private float deltaSpawn=2.0f;
  public Transform trail;
  private Collider2D[] fruitCols;
  private Vector3 lastmousepos;

  // Use this for initialization
  private void Start () {
    fruitCols=new Collider2D[0];
  }

  private Fruits GetFruits ()
  {
    Fruits f = fruties.Find (x=>!x.IsActive);
    if (f==null)
    {
      f = Instantiate (fruitPrefab).GetComponents<Fruits>();

      fruties.Add (f);
    }
    return f;
  }
}

```

# Answer
> 2 votes
As stated in the official documentation, `GetComponents<T>` will return `T[]`, or in your case, `Fruits[]`.

You probably want to use `GetComponent<T>` instead that will return a single `Fruit`, which is the same type of your `f` variable.

---
Tags: unity
---


# Question
Title: Behavior after collision using masks overlap
I'm using masks to make collision detection in a game using pygame. The detection works well, but I have had problems with the behaviour after collision.

In most games, the obstacles are vertical or horizontal, making easy manipulate the velocity of objects moving. So, if the object collide, there is just two options: cancel x component or cancel y component. In this way, the object stop the move only in the normal direction.

But, my obstacles have any shape (not any, just rectangles and triangles) and direction, making things hard.

Basically, I want to cancel the velocity component in the normal direction to obstacle in the collision point.

Some help?

Thanks

# Answer
> 2 votes
So it appears as you are actually asking how to find the normal on an arbitrary pixel mask, this is actually simple.

One method you might think of using, is to simply use the pixel mask pixel as a AABB collision. This can work, but has the unfortunate problem of potentially stoping your character from moving. If it is coarse enough though, you can merely treat it the same as you would with colliding against your boxes.

But you will run into issues where you collided and you get this result:

when what you probably wanted was this:

To solve this you need to use the pixel neighborhood in order to figure out the real "surface". for the intersected pixel, check the surrounding neighbor intersecting pixel, find the pixel which is the closest in direction to the colliding object impact direction vector (the negative of its velocity vector) and use the line created by these two points as the plane to create the normal from. To find out the normal for a line segment via the formula found here. Using this we can use the normal. here is a picture of what I'm talking about:

To use the normal, you will want to calculate the impulse on your colliding objects velocity with the surface normal, which will allow you to remove the part of your velocity which is normal to the surface.

---
Tags: collision-detection, pygame
---