# Question
Title: Understanding use of dot product in speed boost pad
I am trying to understand the dot product. I have found a website that gives you intuition about this topic and one of the examples involves a speed boost pad:

> Imagine the red vector is your speed (x and y direction), and the blue vector is the orientation of the boost pad (x and y direction). Larger numbers are more power.
>
> How much boost will you get? For the analogy, imagine the pad multiplies your speed:
>
> * If you come in going 0, you'll get nothing \[if you are just dropped onto the pad, there's no boost\]
> * If you cross the pad perpendicularly, you'll get 0 \[just like the banana obliteration, it will give you 0x boost in the perpendicular direction\]
>
> But, if we have some overlap, our x-speed will get an x-boost, and our y-speed gets a y-boost:
>
> \\$\text{Total} = speed\_x \cdot boost\_x + speed\_y \cdot boost\_y\\$
>
> Neat, eh? Another way to see it: your incoming speed is \\$\\|a\\|\\$, and the max boost is \\$\\|b\\|\\$. The percentage of boost you actually get (based on how you're lined up) is \\$\cos(θ)\\$ , for a total of \\$\\|a\\| \\|b\\|\cos(θ)\\$.

Let's say we have an object moving with a speed v of \<3,3\> at an angle of 45 degrees and a boost pad p of \<10,0\>. I am looking to see the increase of vector v when it hits the pad.

I have calculated the dot product obtaining a value of 30. My questions are:

* how does this value modify the speed vector?
* And what does this value actually represent? The new total length of v? Does it modify only the x coordinate of v?
* And how do I add it over the initial vector? What would be the new speed vector after the interaction with the boost pad?
* If we are to normalize the vectors and calculate the dot product, we get a value of around 0.70(cos 45). How is this value to be used on the current speed vector v\<3,3\>? And what does this percentage represent?

Also, I imagine that the new value for the vector would be just for the frame where it hits the pad, thus to make use of the boost a timer should be added before the speed comes back to normal.

# Answer
> 0 votes
It sounds like the author envisions the mechanic working something like this:

```
Vector3 boostDirection = Vector3.Normalize(pad.boostVector);
float boostFactor = Vector3.Dot(boostDirection, car.Velocity);

boostFactor = Mathf.Max(boostFactor, 0);

Vector3 velocityChange = pad.boostVector * boostFactor;
// Equivalently:
// velocityChange = new Vector3(
//                     pad.boostVector.x * boostFactor,
//                     pad.boostVector.y * boostFactor,
//                     pad.boostVector.z * boostFactor
//                );

car.velocity += velocityChange;

```

They don't explicitly state that the boost factor should be clamped so it doesn't drop below zero, but I'd recommend this to avoid getting a boost *backward* if you drive across the pad the other way (unless you want a bi-directional race of some kind).

Note that since we normalized the pad's vector to a unit vector direction first, we've taken its length out of the dot product equation, leaving \\$\text{boostFactor} = \\| \text{car.velocity} \\| \cos(\theta)\\$, where \\$\theta\\$ is the angle between the car's direction of motion and the boost pad's direction.

So then when we multiply this scalar by the original boost vector, we re-introduce that vector's length, getting a total velocity change with magnitude:

$$\begin{align} \\| \text{velocityChange} \\| &= \\| \text{pad.boostVector}\\|\\| \text{car.velocity} \\| \cos(\theta)\\ &= \text{pad.boostVector} \cdot \text{car.velocity} \end{align}$$

Here the length of the pad's boost vector represents a multiplier on the incoming velocity: a length of 1 means your extra boost is 100% of your incoming velocity if you match the pad direction perfectly. A length of 0.5 means you'll get an extra 50% of your incoming velocity, etc.

Doing it this way, the velocity change is always pointing in the direction of the pad, so if you drive across it at a diagonal, you'll get a nudge to redirect you forward according to the pad's direction, helping you stay on-track even if you veered sideways quickly to catch the boost pad. (I chose to show this style because anecdotally, that's the behaviour I'm used to seeing in racing games - though it's been a while since I played this particular Mario Kart so I don't recall whether that's how they do it)

You could instead choose to normalize the velocity, not the boost vector, and multiply the velocity by the boost factor to get the velocity change. That would give you a boost pad that sill gives you the same magnitude of extra velocity, but preserves your incoming direction: drive across the pad diagonally, and you'll be accelerated diagonally.

Note that this is a good example for showing the *kind of thing* we might use dot products for, but it's likely not exactly how Mario Kart or other racers implement their boosts. A few considerations we'd often apply when fleshing this out to a real game feature:

* Fine-grained degrees of success depending on how perfectly you match the pad's angle can feel inconsistent to the player. You'll almost never get the perfect 0-degree-deviation 100% boost.

So in practice, games will often "bucket" the angle into coarser wedges. Say you get a 100% boost if you're aligned within 5 degrees, and a 75% boost if you're aligned within 45 degrees. This helps with the perceived consistency, and players can clearly feel the difference between hitting the boost "perfectly" and "almost" because there's a discrete jump in the effect (and sounds/visuals we use) rather than a smooth gradient of intermediate degrees.

We'll still use dot products to compute your alignment and find the correct bucket, we just won't use the dot product directly as the boost factor.
* Similarly, we'll often have a more restrictive tolerance for what's needed to activate the boost. With the model in the example, if you drive across the pad at an angle of 89 degrees to its direction, you still get a boost.

Many games will set a higher tolerance before you hit the "minimum boost" bucket, so you have to be travelling at most 45-60 degrees from the pad's direction for it to activate.
* We'll usually enforce a maximum speed, so that hitting a chain of boosts doesn't multiply your speed exponentially and rocket you out of the level entirely.
* We'll often "bucket" the velocity change too, similar to how we bucket the angles, for similar consistency reasons.

Say this boost pad is on a jump to the next segment of track, and the player just landed it on their previous lap. This time, they hit the same boost pad but with 5% less incoming speed. The player probably can't perceive that they did anything differently this time, but if we use the formula above and give them 5% less boost, they end up missing the jump and it looks like the game cheated them!

So for this type of boost pad, we'd often make it give a fixed amount of extra velocity over a range of speeds, so if you hit it anywhere within this tolerance zone you get the full boost you expect. (Though this "full boost amount" could still depend on which car you're using)

So take this example for what it is: a way to illustrate a situation where dot products are useful, but not as a prescription for how boost pads must be implemented. Like any game mechanic, there are lots of different ways we can choose to implement it to get different effects.

---
Tags: vector, game-mechanics, linear-algebra, racing, vehicle
---


# Question
Title: How to perform some custom math between the model matrix and the projection matrix?
I'm trying to write a shader in Unity that will perform some custom math after the `model*view` matrix is applied but before the `projection` matrix is applied.

First off, I'm not sure whether I should be using a surface shader or an unlit shader. My impression is that a surface shader can do everything I need it to and the outcome will look better with less effort, is that right?

I'm thinking that what I can do is manually apply the model and view matrices in the vertex shader, and then I have to tell it somehow to only apply the projection matrix in the rasterization step. Any idea how to go about this, or a different way to achieve the same result?

# Answer
> 1 votes
Here's a modified version of the default unlit vertex shader that shows how to break `UnityObjectToClipPos` into two steps, with a layover in camera view space in between.

```
v2f vert (appdata v)
{
    v2f o;

    // Ordinarily, we'd go all the way from object space to clip space in one operation:
    // o.vertex = UnityObjectToClipPos(v.vertex);

    // But instead, we'll first go from object space to world space to view space:
    float3 viewSpace = UnityObjectToViewPos(v.vertex);

    // Then do some math in view space... Here I exchange x & y for a weird effect. :)
    viewSpace.xy = viewSpace.yx * float2(-1, 1);

    // Then finally project the view space position into clip space:
    o.vertex = mul(UNITY_MATRIX_P, float4(viewSpace, 1));

    // And the rest of the shader can stay unchanged.

    o.uv = TRANSFORM_TEX(v.uv, _MainTex);
    UNITY_TRANSFER_FOG(o,o.vertex);
    return o;
}

```

If you want to do this with a surface shader, it's a bit more tricky, since their vertex modification happens in local space. We need to transform to view space, apply our adjustments, then transform *back* to local space for the vertex to be in the right space for the rest of the pipeline to work with:

```
// Modify your surface shader declaration to point at the vertex-modifying function
#pragma surface surf Standard fullforwardshadows vertex:vert

// ...then provide the function lower down.

void vert(inout appdata_full v) {
    // As before, we transform into view space first.
    float3 viewSpace = UnityObjectToViewPos(v.vertex);

    // Do some math on our vertex in that space...
    viewSpace.xy = viewSpace.yx * float2(-1, 1);

    // Now the tricky part: getting back. We don't have an inverse view
    // matrix by default (though a script could provide this for us).

    // Instead, we'll take advantage of the fact that the camera view matrix
    // is just a rotation and translation, and the inverse of a rotation
    // is its transpose (much cheaper to calculate in a shader):
    float4x4 viewMatrix = UNITY_MATRIX_V;
    float3 translation = float3(viewMatrix[0][3], viewMatrix[1][3], viewMatrix[2][3]);

    viewMatrix[0][3] = 0;
    viewMatrix[1][3] = 0;
    viewMatrix[2][3] = 0;

    // Pseudo-inverse: undo the translation, then the rotation.
    viewSpace -= translation;
    float4 worldSpace = mul(transpose(viewMatrix), float4(viewSpace, 0));
    worldSpace.w = 1;

    // Now for the final hop from world space back to object space.
    v.vertex = mul(unity_WorldToObject, worldSpace);
}

```

Note that neither version I've shown touches your normal vectors. Be aware that these are not automatically recalculated when you change your vertices. So, if you alter your shape in such a way that its surface normals or lighting should be affected, be sure to apply a corresponding transformation to the normal vectors while you're at it.

---
Tags: unity, shaders, hlsl
---


title: Unity - change API level

text:
# Question
Title: Unity - change API level
I tried uploading a game to google play. But I got a warning that the API level needs to be changed to a diferent one. I'm not sure how to do that in Unity as I had not configured it before. Can someone please help. I have attached a screenshot of the warning.

# Answer
This question doesn't demonstrate research effort. Searching Unity Android API Level will lead you to the documentation for Android Player Settings, including:

> **Minimum API Level** Minimum Android version (API level) required to run the application.
>
> **Target API Level** Target Android version (API level) against which to compile the application.

Here you'll find a drop-down to select your target API level:
> 2 votes

# Answer
Open \[Android Studio -\> SDK Manager -\> Android SDK -\> SDK Platforms\] and download Android 10.0 (Q)

Make sure that in PlayerSettings (Ctrl+Shift+B -\> Player Settigns) Target API Level is `Automatic (highest installed`.
> 1 votes

---
Tags: unity, api
---


# Question
Title: What is the difference between these two shaders in terms of performance?
I have implemented a two pass Gaussian blur shader in GLSL like this:

```
...
const float[] weights = float[](0.382928, 0.241732, 0.060598, 0.005977, 0.000229);
vec2 offset = vec2(1.0f) / vec2(textureSize(image, 0));
vec3 result = texture(image, vec3(io_textureCoordinates, layer)).rgb * weights[0];
if(horizontal) {
  for(int i = 1; i < weights.length(); i++){
    result += texture(image, vec3(io_textureCoordinates + vec2(offset.x * float(i), 0.0f), layer)).rgb * weights[i];
    result += texture(image, vec3(io_textureCoordinates - vec2(offset.x * float(i), 0.0f), layer)).rgb * weights[i];
  }
} else {
  for(int i = 1; i < weights.length(); i++){
    result += texture(image, vec3(io_textureCoordinates + vec2(0.0f, offset.y * float(i)), layer)).rgb * weights[i];
    result += texture(image, vec3(io_textureCoordinates - vec2(0.0f, offset.y * float(i)), layer)).rgb * weights[i];
  }
}
...

```

Where variable horizontal and layer are uniforms (the image is a texture2DArray, but this is not that important). I use a 9x9 kernel (variable weights, the first weight is the center) and first I blur the image horizontally, then I change the horizontal uniform to false and rerun the shader to blur the image vertically. It works fine, but the performance is really bad. I don't know why, because I don't do anything special. The variable horizontal is a uniform, so it remains the same for every pixel in a draw call, so each shader core executes the the same path for every pixel.

Then I changed the code a little bit, like this:

```
...
const float[] weights = float[](0.382928, 0.241732, 0.060598, 0.005977, 0.000229);
vec2 offset = vec2(1.0f) / vec2(textureSize(image, 0));
vec3 result = texture(image, vec3(io_textureCoordinates, layer)).rgb * weights[0];
vec2 ofs = horizontal ? vec2(offset.x, 0) : vec2(0, offset.y);
for(int i = 1; i < weights.length(); i++){
  result += texture(image, vec3(io_textureCoordinates + ofs * float(i), layer)).rgb * weights[i];
  result += texture(image, vec3(io_textureCoordinates - ofs * float(i), layer)).rgb * weights[i];
}
...

```

It's almost the same, I just use horizontal in another place, but the performance is much better. Can someone explain what is the difference between the two shaders what causes a big difference in performance? I thought that maybe the first version executes both sides of the if-else, which means two times more texture sampling, however the second version is much faster even if I execute it two times more.

I'm using WebGL 2 and Nvidia GTX 1050M.

# Answer
```
vec2 ofs = horizontal ? vec2(offset.x, 0) : vec2(0, offset.y);

```

Simple ternary expressions like this can be compiled to a conditional move instruction, with no branching. So your second version eliminates all overhead that might be needed to support the branch.
> 1 votes

---
Tags: shaders, glsl, performance, gpu, blur
---


# Question
Title: How can I make a custom mesh class in Unity?
I'm doing something in Unity where I need to specify the position and orientation of vertices with two `Vector4`s, and they're not just position and normal vectors. I've already written my custom shader and now I need to make mesh objects that can be fed into it.

So how do I make my custom mesh? Should I inherit from the mesh class? Will I still be able to use the normal mesh filter and mesh renderer components or should I replace those too? I am comfortable coding the data structure for my new mesh, the question is interfacing with the Unity rendering pipeline and sending the data to my shader in the right way.

# Answer
> 1 votes
I don't recommend creating a new Mesh class for this.

Instead, send your additional 4D data to the GPU as texture coordinates. Don't let the name fool you - these don't need to have anything to do with textures, they're just streams of arbitrary float data you can use however you want in the shaders.

This might look something like this:

```
void Add4DMeshData(Mesh source) {
    var vertices = mesh.vertices;
    var normals = mesh.normals;
    var positions = new Vector4[vertices.Length];
    var orientations = new Vector4[vertices.Length];

    for(int i = 0; i < vertices.Length; i++) {
        positions[i] = Get4DPosition(vertices[i]);
        orientations[i] = Get4DOrientation(normals[i]);
    }

    mesh.SetUVs(0, positions);
    mesh.SetUVs(1, orientations);
}

```

Your shader can then read these streams in its input struct...

```
struct vs_input {
    float4 position    : TEXCOORD0;
    float4 orientation : TEXCOORD1;
    // etc...
};

```

...and do whatever you need with them, no new Mesh class required.

---
Tags: unity, rendering, mesh, gpu
---


# Question
Title: Unity: how do I get a list of prefab tiles from the TileMap?
I'm building a 2D strategy game where I've decided to use TileMap for spaces which characters can traverse. My tiles need to be prefabs, because they will have a script attached to them to store things like their type, cost, any effects they might have on them, name, etc.

To build the TileMap I imported Unity 2D Extras and used its **prefab brush**. I've actually tried this a couple of ways. First I just manually placed the prefabs and dragged them into the hierarchy under GameTileMap. When that didn't work I thought maybe I needed to do it with the prefab brush so I deleted everything and did the whole thing again that way. Still nothing.

Here is how my Hierarchy looks:

And this is the code I used to try and get that list of all the Tile prefabs I have there:

```
using UnityEngine.Tilemaps;
using UnityEngine;

public class TileManager : MonoBehaviour {

  public static TileManager instance;
  public Tilemap Tilemap;

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

    // Do I even have any tiles?
    TileBase[] allTiles = Tilemap.GetTilesBlock(Tilemap.cellBounds);

    // Print positions of each tile if I have any.
    foreach (Vector3Int pos in Tilemap.cellBounds.allPositionsWithin) {
      var localPlace = new Vector3Int(pos.x, pos.y, pos.z);
      Debug.Log(localPlace);
    }

  }
}

```

The above code is on my TileManager. When run, `allTiles` list is empty so of course no Debug output is logged.

**Question:**

Is it possible to get list of tiles that have been painted with the prefab brush?

# Answer
So to recap:

**Initial Problem**

* Desire to create a tile map using the TileMap feature with 2d-extras
* Above mentioned tiles should be able to store data about themselves. Data like cost, type, etc.
* Must be able to be referenced in code. i.e read them in from the tile map

**Round Peg Square Hole**

* Attempted to create these tiles as prefabs.
* Created scripts to attach to each prefab that would store said data
* Attempted to use the prefab brush to paint these tiles as prefabs with the expectation that I could get them from the tilemap in code.

***Results***

* Prefabs were not added as part of the tilemap

***Correct Solution***

* Scriptable tiles solved all initial problems

The way this works is you create an editor script call `<MyTileType>`, in my case `TerrainTile`. This script is going to add an option in your Assets/Create menu that will have the name you choose and that will create a `.asset` file with that name.

`.asset` files can be dragged into the tile palette. Your class will inherit from `UnityEngine.Tilemaps.TileBase` and in there you can store w/e data you want. Once you have this, the world is yours.

**Links that lead me to victory**

**Some things that weren't immediately obvious if you've never written any editor scripts before**

* I needed to set my sprite import settings for my terrain asset's PPU to match the file size (in my case 1024 x 1024) so that it scaled perfectly to my grid.
* Class structure needs to be like:

```
#if UNITY_EDITOR
using UnityEditor;
#endif

public class TerrainTile : TileBase
{
  // W/e fields you want.
  [SerializeField]
  private Sprite[] _sprite = default;

  [SerializeField]
  private int _cost = 0;

// Must be inside the class you're trying to use
---------------------------------------------------
#if UNITY_EDITOR
  // The following is a helper that adds a menu item to create a MyTile Asset
  [MenuItem("Assets/Create/TerrainTile")]
  public static void CreateTerrainTile() {
    string path = EditorUtility.SaveFilePanelInProject("Save Terrain Tile", "New Terrain Tile", "Asset", "Save Terrain Tile", "Assets");
    if (path == "")
      return;
    AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<TerrainTile>(), path);
  }
#endif
---------------------------------------------------

  public override void RefreshTile(Vector3Int position, ITilemap tilemap) {
    // Read docs for an explanation on this.
    tilemap.RefreshTile(position);
  }

  public override void GetTileData(Vector3Int position, ITilemap tileMap, ref UnityEngine.Tilemaps.TileData tileData) {

    // This is for the preview in the tile palette.
    tileData.sprite = _sprite[0];
  }
}

```

Its clear that the prefab brush was not built for this. It seems intended to be used to simply paint sparsely used prefabs such as items, scenery, etc.
> 1 votes

---
Tags: unity, 2d, tilemap, prefabs
---


# Question
Title: Why when I'm changing the terrain position it's not creating the cubes on the terrain?
```
using UnityEngine;

public class TileTest : MonoBehaviour
{
    public int Rows;
    public int Columns;
    public float TileWidth = 1;
    public float TileHeight = 1;

    [HideInInspector]
    public Vector3 MarkerPosition;

    private void OnDrawGizmosSelected()
    {
        var mapWidth = this.Columns * this.TileWidth;
        var mapHeight = this.Rows * this.TileHeight;
        var position = this.transform.position;

        Gizmos.color = Color.white;
        Gizmos.DrawLine(position, position + new Vector3(mapWidth, 0, 0));
        Gizmos.DrawLine(position, position + new Vector3(0, mapHeight, 0));
        Gizmos.DrawLine(position + new Vector3(mapWidth, 0, 0), position + new Vector3(mapWidth, mapHeight, 0));
        Gizmos.DrawLine(position + new Vector3(0, mapHeight, 0), position + new Vector3(mapWidth, mapHeight, 0));

        Gizmos.color = Color.grey;
        for (float i = 1; i < this.Columns; i++)
        {
            Gizmos.DrawLine(position + new Vector3(i * this.TileWidth, 0, 0), position + new Vector3(i * this.TileWidth, mapHeight, 0));
        }

        for (float i = 1; i < this.Rows; i++)
        {
            Gizmos.DrawLine(position + new Vector3(0, i * this.TileHeight, 0), position + new Vector3(mapWidth, i * this.TileHeight, 0));
        }

        Gizmos.color = Color.red;
        Gizmos.DrawWireCube(this.MarkerPosition, new Vector3(this.TileWidth, this.TileHeight, 1) * 1.1f);
    }

    public void GenerateNewMap()
    {

    }

    public void DestroyMap()
    {
        var Tiles = GameObject.FindGameObjectsWithTag("Tile");
        foreach (GameObject tile in Tiles)
        {
            DestroyImmediate(tile);
        }
    }
}

```

Then the editor :

```
using System;
using UnityEditor;
using UnityEngine;

[CustomEditor(typeof(TileTest))]
public class TileMapEditor : Editor
{
    private Vector3 mouseHitPos;

    public override void OnInspectorGUI()
    {
        TileTest Generate = (TileTest)target;

        if (GUILayout.Button("Generate Map", GUILayout.Width(100), GUILayout.Height(30)))
        {
            Generate.GenerateNewMap();
        }

        DrawDefaultInspector();

        if (GUILayout.Button("Destroy Map", GUILayout.Width(100), GUILayout.Height(30)))
        {
            Generate.DestroyMap();
        }
    }

    private void OnSceneGUI()
    {
        if (this.UpdateHitPosition())
        {
            SceneView.RepaintAll();
        }

        this.RecalculateMarkerPosition();

        Event current = Event.current;

        if (this.IsMouseOnLayer())
        {
            if (current.type == EventType.MouseDown || current.type == EventType.MouseDrag)
            {
                if (current.button == 1)
                {
                    this.Erase();
                    current.Use();
                }
                else if (current.button == 0)
                {
                    this.Draw();
                    current.Use();
                }
            }
        }

        Handles.BeginGUI();
        GUI.Label(new Rect(10, Screen.height - 90, 100, 100), "LMB: Draw");
        GUI.Label(new Rect(10, Screen.height - 105, 100, 100), "RMB: Erase");
        Handles.EndGUI();
    }

    private void OnEnable()
    {
        Tools.current = Tool.View;
        Tools.viewTool = ViewTool.FPS;
    }

    private void Draw()
    {
        var map = (TileTest)this.target;
        var tilePos = this.GetTilePositionFromMouseLocation();
        var cube = GameObject.Find(string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y));

        if (cube != null && cube.transform.parent != map.transform)
        {
            return;
        }

        if (cube == null)
        {
            cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        }

        var tilePositionInLocalSpace = new Vector3((tilePos.x * map.TileWidth) + (map.TileWidth / 2), (tilePos.y * map.TileHeight) + (map.TileHeight / 2));
        cube.transform.position = map.transform.position + tilePositionInLocalSpace;
        cube.transform.localScale = new Vector3(map.TileWidth, map.TileHeight, 1);
        cube.transform.parent = map.transform;
        cube.name = string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y);
        cube.tag = "Tile";
    }

    private void Erase()
    {
        var map = (TileTest)this.target;
        var tilePos = this.GetTilePositionFromMouseLocation();
        var cube = GameObject.Find(string.Format("Tile_{0}_{1}", tilePos.x, tilePos.y));

        if (cube != null && cube.transform.parent == map.transform)
        {
            UnityEngine.Object.DestroyImmediate(cube);
        }
    }

    private Vector2 GetTilePositionFromMouseLocation()
    {
        var map = (TileTest)this.target;
        var pos = new Vector3(this.mouseHitPos.x / map.TileWidth, this.mouseHitPos.y / map.TileHeight, map.transform.position.z);

        pos = new Vector3((int)Math.Round(pos.x, 5, MidpointRounding.ToEven), (int)Math.Round(pos.y, 5, MidpointRounding.ToEven), 0);

        var col = (int)pos.x;
        var row = (int)pos.y;
        if (row < 0)
        {
            row = 0;
        }

        if (row > map.Rows - 1)
        {
            row = map.Rows - 1;
        }

        if (col < 0)
        {
            col = 0;
        }

        if (col > map.Columns - 1)
        {
            col = map.Columns - 1;
        }

        return new Vector2(col, row);
    }

    private bool IsMouseOnLayer()
    {
        var map = (TileTest)this.target;

        return this.mouseHitPos.x > 0 && this.mouseHitPos.x < (map.Columns * map.TileWidth) &&
               this.mouseHitPos.y > 0 && this.mouseHitPos.y < (map.Rows * map.TileHeight);
    }

    private void RecalculateMarkerPosition()
    {
        var map = (TileTest)this.target;
        var tilepos = this.GetTilePositionFromMouseLocation();
        var pos = new Vector3(tilepos.x * map.TileWidth, tilepos.y * map.TileHeight, 0);

        map.MarkerPosition = map.transform.position + new Vector3(pos.x + (map.TileWidth / 2), pos.y + (map.TileHeight / 2), 0);
    }

    private bool UpdateHitPosition()
    {
        var map = (TileTest)this.target;
        var p = new Plane(map.transform.TransformDirection(Vector3.forward), map.transform.position);
        var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition);
        var hit = new Vector3();
        float dist;

        if (p.Raycast(ray, out dist))
        {
            hit = ray.origin + (ray.direction.normalized * dist);
        }

        var value = map.transform.InverseTransformPoint(hit);

        if (value != this.mouseHitPos)
        {
            this.mouseHitPos = value;
            return true;
        }

        return false;
    }
}

```

Then in the editor script I added at the bottom the method :

```
public void TerrainObjects(GameObject gameobject)
    {
        Terrain terrain = Terrain.activeTerrain;
        var cube = GameObject.Find(string.Format("Terrain_{0}_{1}", gameobject.transform.position.x, gameobject.transform.position.y));
        if (cube != null)
            return;

        if (cube == null)
        {
            cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        }

        cube.transform.position = new Vector3(terrain.transform.position.x + gameobject.transform.position.x, 0, terrain.transform.position.z + gameobject.transform.position.y);
        cube.transform.localScale = new Vector3(gameobject.transform.localScale.x, gameobject.transform.localScale.y, 1);
        cube.transform.parent = GameObject.Find("Terrain Map").transform;

        cube.name = string.Format("Terrain_{0}_{1}", gameobject.transform.position.x, gameobject.transform.position.y);
    }

```

This method create cubes on the terrain according to the positions on the grid tile map.

For example let's say the terrain is at position 0,0,0 and the tile map and terrain map objects are child of the terrain and positioned at 0,0,0

Screenshot of the terrain at 0,0,0

Screenshot of the tile map child position 0,0,0

And screenshot of the terrain map child also at 0,0,0

Now I'm clicking with the mouse left button on the grid and create some cubes and it's creating also cubes on the terrain :

Now I moved the terrain to position 10,0,0 Both childs tile map and terrain map moved with the terrain and they are still at 0,0,0

Now I'm clicking with the mouse on the grid again to create cubes and this time it's creating the terrain cubes on the left side of the terrain and not on the terrain.

It's only creating the cubes on the terrain when the terrain is at position 0,0,0

How can I make that no matter where the terrain is at what position the cubes that should be create on the terrain will be on the terrain like when the terrain position is at 0,0,0 and not on the side of the terrain ?

# Answer
Solution is to change to localPositions :

```
public void TerrainObjects(GameObject gameobject)
    {
        Terrain terrain = Terrain.activeTerrain;
        var cube = GameObject.Find(string.Format("Terrain_{0}_{1}", gameobject.transform.localPosition.x, gameobject.transform.localPosition.y));
        if (cube != null)
            return;

        if (cube == null)
        {
            cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        }

        //cube.transform.position = new Vector3(terrain.transform.position.x + gameobject.transform.position.x, 0, terrain.transform.position.z + gameobject.transform.position.y);
        cube.transform.localPosition = new Vector3(terrain.transform.localPosition.x + gameobject.transform.localPosition.x, 0, terrain.transform.localPosition.z + gameobject.transform.localPosition.y);
        cube.transform.localScale = new Vector3(gameobject.transform.localScale.x, gameobject.transform.localScale.y, 1);
        cube.transform.parent = GameObject.Find("Terrain Map").transform;

        cube.name = string.Format("Terrain_{0}_{1}", gameobject.transform.localPosition.x, gameobject.transform.localPosition.y);
        cube.tag = "Terrain Map";
    }

```
> 1 votes

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


# Question
Title: How can I access a GameObject variable in mono script from editor script?
In the mono script :

```
using UnityEngine;

public class TileTest : MonoBehaviour
{
    public GameObject prefabPathOnTerrain;

```

Then in the editor script at the top :

```
private SerializedProperty prefabPathOnTerrain;

```

Then inside OnEnable()

```
private void OnEnable()
    {
        prefabPathOnTerrain = serializedObject.FindProperty("prefabPathOnTerrain");
    }

```

And then inside a method I want to use it as a GameObject : And instead using CreatePrimitive to use Instantiate : But doing :

```
GameObject go = Instantiate(prefabPathOnTerrain);

```

Will not work.

```
public void TerrainObjects(GameObject gameobject)
    {
        Terrain terrain = Terrain.activeTerrain;
        var cube = GameObject.Find(string.Format("Terrain_{0}_{1}", gameobject.transform.localPosition.x, gameobject.transform.localPosition.y));
        if (cube != null)
            return;

        if (cube == null)
        {
              GameObject go = Instantiate(prefabPathOnTerrain);

            //cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
        }

        cube.transform.localPosition = new Vector3(terrain.transform.localPosition.x + gameobject.transform.localPosition.x, 0, terrain.transform.localPosition.z + gameobject.transform.localPosition.y);
        cube.transform.localScale = new Vector3(gameobject.transform.localScale.x, gameobject.transform.localScale.y, 1);
        cube.transform.parent = GameObject.Find("Terrain Map").transform;

        cube.name = string.Format("Terrain_{0}_{1}", gameobject.transform.localPosition.x, gameobject.transform.localPosition.y);
        cube.tag = "Terrain Map";
    }

```

# Answer
> 1 votes
Don't forget to read the documentation for the data types you're using.

A `SerializedProperty` could potentially hold any kind of data the Unity serializer supports. It's like backpack with different zippered pockets for different things you might want to carry. So if you want a particular kind of data out of it, you need to unzip the right pocket.

For a reference to a game object, that's the `.objectReferenceValue` pocket. So you want something like this:

```
var prefab = (GameObject)prefabPathOnTerrain.objectReferenceValue;

```

We have to cast it to the type we expect, because an `objectReferenceValue` could reference any `Object` type.

Then you can check whether the prefab is non-null and instantiate as normal.

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


# Question
Title: Where can I get correct pitch parameter for SDL_RenderReadPixels function in SDL2?
I have a texture created with `SDL_TEXTUREACCESS_TARGET` access and I want to get all its pixels with `SDL_RenderReadPixels()` function. One of the function parameters is `pitch` and I don't really know where can I can get it.

Texture is created with dimensions of a previously created surface, but function call with `surface->pitch` as pitch parameter generates `EXC_BAD_ACCESS`.

Texture and surface dimensions are 800x600, and `surface->pitch` returns 3200, which is strange for me, because I thought that pitch is the width of the texture in memory and expected `surface->pitch` to be something like 1024.

# Answer
> 4 votes
Pitch: the length of a row of pixels in bytes

Basically, if your texture/surface is 800px wide, and you have 4 bytes per pixel (32bit colour) then the pitch is 800x4 = **3200**.

Use SDL\_QueryTexture() to get texture format, the format can tell you how many bytes per pixel.

```

    SDL_QueryTexture(texture, &format, NULL, NULL, NULL);
    // Parse format with a switch

```
QueryTexture can also tell you the Access type, Width and Height.
> SDL\_PIXELFORMAT\_RGB332 //8bit colour

...

> SDL\_PIXELFORMAT\_RGB555 //15bit/16bit colour

...

> SDL\_PIXELFORMAT\_ABGR8888 //32-bit colour

Note the last 3-4 numbers tell you how many bits are used for each colour, add them together to get the number of bits per pixel (bpp), then multiply bpp by width to get pitch.

# Answer
> 2 votes
You should use the pitch parameter of the surface, otherwise you're guessing. This is because the pitch can be padded on different systems or video cards (for extra data or optimization purposes -- any reason the vendor needs).

The only way to know for sure is to query the pitch value, otherwise you leave your program vulnerable to break on an unknown number of systems. It might be a large percentage or small percentage of systems, but either way it's a simple problem to avoid.

You stated that passing `surface->pitch` as a parameter causes an error. Possible causes are the surface being freed sooner in the program flow, the surface pointer not being assigned after initialization, or `surface` is pointing to an invalid/expired reference. You might also need to lock your surface before calling `SDL_RenderReadPixels()` as that might cause an access error as well.

Worst case, as a work-around, you can grab the pitch value early on (like right after you create the surface) and store it in a variable, and then pass that in as the pitch argument later.

* *It appears that there's some point in your code where calling `surface->pitch` doesn't cause an error -- since you stated that "`surface->pitch` returns 3200".*

---
Tags: sdl, sdl2
---


# Question
Title: Move objects in array with positions array
I am trying to get a line of spheres to move around but all i get is the first sphere to move and get the rest to follow as one instead of building a sort of a train of spheres. Any idea how to alter the code to get it right? In the code bellow i get the first pbject in listBalls to move nicely along the Bezier curve but the rest move as one and overlap with the first sphere too.

```
    void Update()
{

    t += Time.deltaTime * 0.2f;
    ballPosition = Mathf.Pow(1 - t, 3) * p0 + 3 * Mathf.Pow(1 - t, 2) * t * p1 + 3 * (1 - t) * Mathf.Pow(t, 2) * p2 + Mathf.Pow(t, 3) * p3;
    positions.Add(ballPosition);
    listBalls[0].transform.position = positions[j];
    for (i = 1; i < listBalls.Count; i++)
    {
        Transform ball = listBalls[i].transform;
        Transform nextBall = listBalls[i - 1].transform;
        if ((ball.position - nextBall.position).magnitude > 1f)
        {
            ball.position = positions[j];
        }
    }
    j++;

```

Feels like it should be something easy, setting the N-1 balls to same position as the first ball must be wrong. I tried setting them at positions\[j-2\] but it didn't work either.

Edit: the Spheres should start rolling left to right one after the other eventually all 10 should be on the screen and when they reach P3 they should restarting the rolling.

* listBalls is the List with 10 spheres
* positions is the List with 50 Vector3 positions along the curve.

```
[![enter code here][2]][2]

```

# Answer
It looks like you want something like this:

```
t += Time.deltaTime * 0.2f;

ballPosition =     Mathf.Pow(1 - t, 3)                   * p0
             + 3 * Mathf.Pow(1 - t, 2) * t               * p1
             + 3 * (1 - t)             * Mathf.Pow(t, 2) * p2
             +                           Mathf.Pow(t, 3) * p3;
positions.Add(ballPosition);

// Put first ball at the last position in the list. It's our first "leader"
int positionIndex = positions.Count - 1;
Vector3 leaderPosition = positions[positionIndex];
listBalls[0].transform.position = leaderPosition;

for (i = 1; i < listBalls.Count; i++)
{
    // Back up through the positions list until you find one that's 1.0 units
    // or further behind our current "leader" ball.
    do {
        positionIndex--;
    } while ( (positionIndex >= 0 )
         && ( (positions[positionIndex] - leaderPosition).sqrMagnitude < 1f*1f )
    );

    // If we exhausted our available positions, abort
    // and leave the rest of the balls where they are.
    if(positionIndex < 0) break;

    // This position becomes our new leader for the next ball to follow.
    leaderPosition = positions[positionIndex];

    // Position our current ball at this leader position.
    listBalls[i].transform.position = leaderPosition;
}

// Once the whole train of balls has moved past the start of the list,
// we can remove old positions to keep the list from growing without bound.
if(positionIndex > 0);
positions.RemoveRange(0, positionIndex);

// For efficiency, note that using a circular buffer here will save you the
// copying cost of shifting all the list entries down each time.

```
> 0 votes

---
Tags: unity, movement
---


title: Best Practices for Locating Clicks

text:
# Question
Title: Best Practices for Locating Clicks
I am building a 2D board game in Unity with a static camera pointed down at the game board. During the active phase of each player's turn, I want to detect where they click on the board. Fortunately, the board is laid out in an easy rectangular grid. (Essentially a trio of 5x5 grids).

Which of the following would be best practice to implement this?

1. Create invisible colliders for every square on the board and create a translation function that translates those back to board positions (5,3) with Raytracing?
2. Get the translated coordinates of the click and use a function to figure out which square (if any) the click is in using the mouseclick event handler (by calculating which square the grid coordinates fall in)?
3. Make each square a button with its grid identity encoded and use that in its `OnPressed` function?

Edit: 4) Some other idea I haven't thought of yet?

Experience level: I'm just learning Unity, but have written a lot of C# (and tons of other code).

# Answer
> 3 votes
As with every problem, there are many ways to come to a solution. But one solution I usually find the easiest to implement is:

1. Add an EventSystem to your scene. Which happens automatically when you add a Canvas for your UI.
2. Add a Physics Raycaster component to your camera (Physics Raycaster 2D if you want to use 2d colliders)
3. Add an appropriately shaped Collider to every object you want to be clickable (a Collider2D if you've chosen the PhysicsRaycaster2D).
4. Add a script to those objects which implements the interface `IPointerClickHandler`.

Now every mouse-click will call `OnPointerClick(PointerEventData pointerEventData)` on the object under the cursor. You just need to implement it.

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


# Question
Title: Creating Compute Shaders throws E_INVALIDARG exception in SharpDX
I've recently been working on a small helper for creating and using compute shaders in C# along with Monogame/XNA. My end goal is simply to have compute shaders working in C#.

My main issue is as such:

```
   var result = SharpDX.D3DCompiler.ShaderBytecode.CompileFromFile(filepath, "CSMain", "cs_5_0", ShaderFlags.Debug);
   if (result.ResultCode.Failure)
      throw new Exception($"HLSL Compilation failed with the code: [{result.ResultCode.Code}] and message: [{result.Message}]");
   shader = new SharpDX.Direct3D11.ComputeShader(device, result.Bytecode);

```

Calling the constructor on the ComputeShader class throws the error: "HRESULT: \[0x80070057\], Module: \[General\], ApiCode: \[E\_INVALIDARG/Invalid Arguments\], Message: The parameter is incorrect." (Of type SharpDXException). The device is obtained via `Microsoft.Xna.Framework.Graphics.GraphicsDevice.Handle` casted to a D3D11 `Device`.

Call Stack:

Anyone know how to fix this? Or is this just something I'll have to find some new way of doing?

NOTE:
The fact that I went down the Monogame-DirectX + SharpDX route is largely incidental, but I don't seem to have many options - something like Vortice.Windows, which aims to replace the now abandoned SharpDX, doesn't appear to have compute shader support. While I wouldn't mind using OpenGL, and would be happy with being recommended working .Net Core OpenGL binding libraries (Vulkan would probably be way over my head), that type of question isn't accepted here, but I'm aware it may be the better option.

# Answer
The device from `Microsoft.Xna.Framework` is Direct3D 9, which isn't going to support Direct3D 11 features.

> Why not use SharpDX to create the device so you know it's Direct3D 11?
> 0 votes

---
Tags: c#, directx, directx11, sharpdx, .net
---


# Question
Title: Particle Turbulence Effect in Babylon.js
Is there any way to implement a turbulence effect in a babylon.js Particle System? I know that its possible to use physics engines on mesh objects, but I've not seen any discussion of using them on a babylon particle system.

Might there be a way to bake a particle system as a .vdb and import it if real-time simulation is not an option?

# Answer
> 1 votes
You can use a noise texture to "perturbate" the position of particles. The noise texture is used to apply changes in the direction of the particles.

```
   var noiseTexture = new BABYLON.NoiseProceduralTexture("perlin", 256, scene);
   noiseTexture.animationSpeedFactor = 5;
   noiseTexture.persistence = 2;
   noiseTexture.brightness = 0.5;
   noiseTexture.octaves = 2;

   particleSystem.noiseTexture = noiseTexture;
   particleSystem.noiseStrength = new BABYLON.Vector3(100, 100, 100);

```

Demo can be found here: https://www.babylonjs-playground.com/#R1JWLA#3 -

---
Tags: javascript, babylonjs
---


# Question
Title: Is there a generic name for the "layered" dictionary typically used in mod-capable games?
I'm asking here rather than on SO/SE/CS because I'll probably have less to explain what I'm talking about...

I hope a lot of the users here are familiar with how many games implement modding (or sometimes even their own add-ons, levels etc.) Conceptually, what I've seen most often is a data structure that acts like a layered dictionary. With no mods, there's lookup in the base dictionary layer; whenever a mod is added/enabled, it comes with its own dictionary layer from which lookups are served first, with fallback to the underlying layers if a key is not found. (Note that I'm *not* talking about a nested dictionary.)

So, my question is simply if there's a generic name for this data structure. (Googling for "layered dictionary", which is how I dubbed it, doesn't turn up anything useful...) In the world of file systems, the closest thing that probably resembles it is a union mount. Alas "union dictionary" doesn't get any useful results either... (Also the word "union" is rather misleading in this context because there's an order in the layers of a "union mount".)

Added: By the way, I'm not asing how to implement it, as that's rather obvious from the description. Perhaps that's why no name have been devised for it... Also most game engines I've seen implement multi-layer (not just two) and some allow the (top) layers to be removed at any time so you can do (game) "levels" that way; others require an engine restart so it's only usable for "global mods", i.e. they optimize lookup time by "flattening" the layers down to one as they are added, which is basically why they need an "engine restart" to remove a layer.

Also, it seems the R (statistical) programming language basically has this its `get` functions:

> These functions look to see if each of the name(s) `x` have a value bound to it in the specified environment. If `inherits` is TRUE and a value is not found for `x` in the specified environment, the enclosing frames of the environment are searched until the name `x` is encountered.

So I guess something like "environments and their enclosures" is one term...

# Answer
The most generic concept seems to be variously called a *spagetti/cactus stack* or *in-/parent-pointer tree* of symbol tables.

Now the first part of this "thing" is also generic, in the sense that the "nodes" can be other things that have a notion of look-up. Come to think of it, "union mounts" and how they're implemented in some game engines actually cactus-stack nested dictionaries, in the sense that they both stack layers and allow path-like ("segmented") keys.

N.B. I've not seen a game engine that allows forks in its look-up structures, i.e. in the full sense of a cactus stack. I've only seen linear stacks of nested dictionaries as the most complex look-up structure actually used for modding/levels support.
> 1 votes

# Answer
Steve Yegge calls this the Properties Pattern. It's a pattern that shows up in so many places that we may not even notice it. He's using it in his game Wyvern.

It shows up in scopes:

```
int x = 5, y = 7;
if (…) {
    int x = 3;
    /* x is 3 here! but y is 7 */
}

```

Here the inner scope has {x: 3} and the outer scope has {x: 5, y: 7}. Any name not found in the inner scope will look in the next outer scope, and this will chain all the way up to the global level.

Class inheritance works this way. If a class Base defines methods `a` and `b`, and a subclass Derived defines `a`, it will find Derived.a when looking for `a`, and `Base.b` when looking for `b`. In Self, LambdaMOO, and JavaScript, object inheritance works this way.

SVG attributes work this way. If you have a `<g fill="red" stroke="blue">` and then a `<rect fill="green">` inside of it, it will use green for the fill and blue for the stroke. The OS/2 operating system had properties defined this way. I'm sure there are plenty more examples.

Each level has a key-value mapping, plus a "parent" or "inherit" or "default" pointer to another such mapping, which can itself have another pointer, etc. Typically *writes* go to the current mapping, but *reads* can go up the chain.

I've been looking for a more authoritative name for this pattern than Steve Yegge's blog post, but that's the best I've found so far.
> 1 votes

---
Tags: data-structure, modding, terminology
---


# Question
Title: How to get width and height from a body in box2d?
I am working on a game in `Libgdx` framework. I have to get width and height from a body in `box2d`. is their any way to get width an d height from a body in `box2d`??

# Answer
Bodies are made up of one or more fixtures and fixtures define a shape. This means, for each fixture, you need to get the shape and its size, then combine those to get the total width and height. It looks like the easiest way is with `getRadius()`, but that doesn't give you much. You may want to get the shape type, then create methods for getting more detailed size information based on the shape type. Iterating through their vertices, to determine the extents.

Better yet, you can maintain your own lookup tables when the objects are created, to find their height and width. Have some kind of object manager that creates your bodies for you, when they're created they store a unique ID in either the user data of the body, or of the fixture. Or, if you're not going to use the user data for anything else, just store the size there.
> 1 votes

# Answer
I know that this is a very old thread but I just made my own way of getting the size of a Body here: https://github.com/Wasupmacuz/Box2DBodySize
Here's the code if links are too spooky for you:

```
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.ChainShape;
import com.badlogic.gdx.physics.box2d.CircleShape;
import com.badlogic.gdx.physics.box2d.EdgeShape;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.Shape;

/**
 * Finds the size (width and height) of a body by checking its fixtures' shapes
 */
public class Sizerinator3000
{
    public static Vector2 getBodySize(Body body)
    {
        float maxTop = 0, maxRight = 0, maxBottom = 0, maxLeft = 0;
        for(Fixture f : body.getFixtureList())
        {
            MyVector4 vec = outerVals(f);
            if(vec.a > maxTop)
                maxTop = vec.a;
            if(vec.b > maxRight)
                maxRight = vec.b;
            if(vec.c > maxBottom)
                maxBottom = vec.c;
            if(vec.d > maxLeft)
                maxLeft = vec.d;
        }

        return new Vector2(Math.abs(maxRight - maxLeft), Math.abs(maxTop - maxBottom));
    }

    public static Vector2 getBodySize(Body body, float scale)
    {
        float maxTop = 0, maxRight = 0, maxBottom = 0, maxLeft = 0;
        for(Fixture f : body.getFixtureList())
        {
            MyVector4 vec = outerVals(f).scale(scale);
            if(vec.a > maxTop)
                maxTop = vec.a;
            if(vec.b > maxRight)
                maxRight = vec.b;
            if(vec.c > maxBottom)
                maxBottom = vec.c;
            if(vec.d > maxLeft)
                maxLeft = vec.d;
        }

        return new Vector2(Math.abs(maxRight - maxLeft), Math.abs(maxTop - maxBottom));
    }

    /**
     * Changing which method is called based on the fixture's shape
     * @param fixture the current fixture being analyzed
     * @return the outermost points of the fixture's shape
     */
    private static MyVector4 outerVals(Fixture fixture)
    {
        Shape shape = fixture.getShape();
        Shape.Type type = shape.getType();
        MyVector4 size = new MyVector4();
        switch(type)
        {
        case Polygon:
        size = shapeVals((PolygonShape)shape);
        break;
        case Chain:
        size = shapeVals((ChainShape)shape);
        break;
        case Edge:
        size = shapeVals((EdgeShape)shape);
        break;
        case Circle:
        size = shapeVals((CircleShape)shape);
        break;
        }

        return size;
    }

    /**
     * Calculates the outermost points for a PolygonShape
     * @param s the shape
     * @return the maximum upper, lower, left, and right values; given by the vertices
     */
    private static MyVector4 shapeVals(PolygonShape s)
    {
        MyVector4 size = new MyVector4(); // top, right, bottom, left
        for(int i = 0; i < s.getVertexCount(); i++)
        {
            Vector2 probe = new Vector2();
            s.getVertex(i, probe);
            if(probe.x > size.b) // right
                size.b = probe.x;
            if(probe.x < size.d) // left
                size.d = probe.x;

            if(probe.y > size.a) // top
                size.a = probe.y;
            if(probe.y < size.c) // bottom
                size.c = probe.y;
        }
        return size;
    }

    /**
     * Calculates the outermost points for a ChainShape
     * @param s the shape
     * @return the maximum upper, lower, left, and right values; given by the vertices
     */
    private static MyVector4 shapeVals(ChainShape s)
    {
        MyVector4 size = new MyVector4(); // top, right, bottom, left
        for(int i = 0; i < s.getVertexCount(); i++)
        {
            Vector2 probe = new Vector2();
            s.getVertex(i, probe);
            if(probe.x > size.b) // right
                size.b = probe.x;
            if(probe.x < size.d) // left
                size.d = probe.x;

            if(probe.y > size.a) // top
                size.a = probe.y;
            if(probe.y < size.c) // bottom
                size.c = probe.y;
        }
        return size;
    }

    /**
     * Calculates the outermost points for an EdgeShape
     * @param s the shape
     * @return the maximum upper, lower, left, and right values; given by the vertices
     */
    private static MyVector4 shapeVals(EdgeShape s)
    {
        MyVector4 size = new MyVector4(); // top, right, bottom, left
        Vector2 probe = new Vector2();
        s.getVertex1(probe);
        if(probe.x > size.b) // right
            size.b = probe.x;
        if(probe.x < size.d) // left
            size.d = probe.x;

        if(probe.y > size.a) // top
            size.a = probe.y;
        if(probe.y < size.c) // bottom
            size.c = probe.y;

        s.getVertex2(probe);
        if(probe.x > size.b) // right
            size.b = probe.x;
        if(probe.x < size.d) // left
            size.d = probe.x;

        if(probe.y > size.a) // top
            size.a = probe.y;
        if(probe.y < size.c) // bottom
            size.c = probe.y;

        return size;
    }

    /**
     * Calculates the outermost points for a CircleShape
     * @param s the shape
     * @return the maximum upper, lower, left, and right values; given by radius and position
     */
    private static MyVector4 shapeVals(CircleShape s)
    {
        MyVector4 size = new MyVector4(); // top, right, bottom, left
        size.a = s.getPosition().y + s.getRadius(); // top
        size.b = s.getPosition().x + s.getRadius(); // right
        size.c = s.getPosition().y - s.getRadius(); // bottom
        size.d = s.getPosition().x - s.getRadius(); // left

        return size;
    }

    /**
     * using this just to store the variables easily
     */
    private static class MyVector4
    {
        public float a, b, c, d;

        public MyVector4()
        {
            this.a = 0;
            this.b = 0;
            this.c = 0;
            this.d = 0;
        }

        @SuppressWarnings("unused")
        public MyVector4(float a, float b, float c, float d)
        {
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
        }

        @SuppressWarnings("unused")
        public void set(float a, float b, float c, float d)
        {
            this.a = a;
            this.b = b;
            this.c = c;
            this.d = d;
        }

        public MyVector4 scale(float val)
        {
            this.a *= val;
            this.b *= val;
            this.c *= val;
            this.d *= val;

            return this;
        }
    }
}

```
> 1 votes

# Answer
You can use this:

`((Sprite)body.getUserData()).getHeight();`

it should answer your question if I guessed your problem correctly.
> 0 votes

---
Tags: libgdx, box2d
---


# Question
Title: What are pros & cons of naming in game currency a standard name vs a gimmick?
We're creating a store and going to add an in game currency. We did a poll and Tokens & Sheep were the top options selected by the players.

I personally think Sheep would be more fun like a barter system as well as it is an in game resource as you may know from the Settlers of Catan (my game https://colonist.io/)

I know that https://starve.io/ has Golden Bread and https://surviv.io/ has Potato as in game currency.

Are there any other such examples? What are the pros cons of such naming?

I don't know any big games which do such a thing.

# Answer
> 5 votes
One problem with using sheep or potatoes as your currency is that it is a bit unintuitive for the player. They might be unsure that this resource is really used *only* as a currency and doesn't fulfill any other mechanical purposes.

When you give the player a sheep, they will wonder what to do with it. Their first ideas will likely be to try to slaughter it for meat or shear it for wool. Or perhaps milk it of sheep's milk? Maybe it's a pet they have to care for? Perhaps they can ride on it? Perhaps it can be combat-trained and used as a companion in battle?

Trading it for other resources would be pretty low on their list of potential uses.

And then there is of course the plausibility problem. A resource which anyone can produce, which is perishable and which isn't perfectly fungible would not make for a very good currency in the real world. But that is of course an issue which can be handwaved away when this resource doesn't have any of these properties in *your* game.

But players will get over that eventually after spending some time with the game. Especially when you make sure your UI design and the tutorial make it clear that sheep are really just a currency and nothing else. So it's really not that much of a problem.

---
Tags: monetization
---


# Question
Title: Why are games built on cross-platform engines sometimes exclusive to Windows?
If an engine supports Windows, OS X, and Linux, why do we sometimes see games using these engines, like *Space Hulk: Deathwing*, restricted to Windows only?

# Answer
> 158 votes
**Technical Reasons:**

* **Game-code made platform specific**: When some developers are making their games, they can sometime rely on platform specific functions. While the game engine might be able to build the game for multiple platforms, the game specific code might make a Windows specific call that either doesn't exist on other platforms or would require remaking a difficult part of the game (Licensing services, File handling systems, etc.).
* **Lack of Capable Machines**: For a long time, most Apple computers did not come with enough graphics power to run most games. So why release somewhere where the users will most likely only have a bad experience? This is slowly changing, thanks to better integrated graphics, but might still be a reason why some go Windows only.
* **Plugin/Library compatibility**: Game developers might use 3rd party libraries to help speed up development or use industry standard/validated code (SSL, Serialisation libraries, etc). If these don't support a platform, the game most likely won't run reliably on it, so certain platforms get excluded unless the developer is willing/able to spend time supporting this code.
* **Increased QA**: During game development, there is a small subsection of the team that ensures that there are no bugs and that the game meets performance standards. Once you add a platform, the game must essentially be tested twice! The generic parts of the game could be left alone, but there is still much more testing to do before release. This can also lead to increased cost, not only with the additional time needed but also specialised hardware, depending on the platform (Apple, Xbox, PlayStation, Phones, etc.).
* **Increased Support**: As games release they will have bugs (some games more than others). As you add more platforms, the amount of post-release support the developer has to do increases. Platform-specific bugs will have to be fixed in a way that fixes it for the broken platform and doesn't affect the platforms which already work. If a platform changes, say, Windows 7 to 8 or an OSX iteration, there will have to be some level of QA required to ensure that there are no bugs on the newer version. And, if there are, that is yet another platform that must be supported alongside the older version. This can have a huge affect on cost, especially after the game has launched (since most revenue is made directly after launch), 3-6 months after release.

**Non-Technical Reasons:**

* **Publisher Agreement**: Some developers will have agreements with the platform holder to release specifically on their platform. While this happens more with consoles, this could also be the case for PC platforms (e.g., Windows).
* **First party Developer**: Some developers are owned by the platform holder and are not allowed to release their games on specific platforms. You likely won't see Halo on PS4 or Forza on Mac.
* **Lack of an audience**: Developers have lots of statistics about consumer trends on specific platforms, especially if they have large publishers with lots of data available. If they have information that says that 90% of their target audience is on Windows, they might not bother to release on other platforms to try and reduce potential bugs or/and keep the marketing material focussed.
* **Does not meet Platform Requirements**: Some platforms such as Apple's App Store have strict requirements on layout and design that need to be followed in order to be published. If a game doesn't meet these requirements for a particular distribution platform, it might not be worth the engineering time to adapt the game and release it if there are not enough predicted sales.
* **Lack of experience with a platform**: If the developer has solely worked with Windows (and there are no/few people with experience of other systems on the team), it might be a lot of work to learn the small differences that can cause issues late in development or there might not be enough budget to hire new staff to be in charge of a Linux/OSX build.
* **Marketing Cost**: if two platforms have significantly different audiences or age groups the marketing material for one may not reach the other meaning that more money must be spent on marketing. If the two groups require different marketing it must all be re-created with the new target audience in mind. Marketing can get extremely expensive especially if you need to reach large audiences, the more platforms need marketing the faster the cost increases.

I'm sure there are more. These are just some of the top of my head. Hope this helps.

# Answer
> 31 votes
Because being available doesn't mean being free & instant.

Supporting one more operating system, in its most simplistic form, means one more platform to provide technical support for.

The more platforms you support = The more platforms you *need to provide* support for = Spending more time on support = Losing work time that could have spent improving your game.

Supporting a platform all comes down to the confidence in which if your game can draw enough playerbase in that target platform, so it makes up for the time you spend providing support for the platform.

# Answer
> 19 votes
There are good answers so far, but let's get to the bottom line.

According to Steam's June 2017 Hardware survey, 96.24% of users sampled used Windows. Of Windows users, 87.37% are either Windows 10 or 7, 64 or 32 bit. OSX variants represent 2.95% of users, and Linux variants total 0.72%.

Time is money. Unless your market is niche and targets OSX or Linux specifically, you'd have to sell a lot of games before \<4% of the market is worth your time, especially as games developers are usually stretched for time to make their product feature complete.

# Answer
> 14 votes
The other answers here are good, but here is one that wasn't mentioned.

I'm having this problem right now - my team is about to release a game made in Unity for Windows/Mac. We've gotten lots of questions as to why our game isn't on mobile. There are 2 main answers:

1) Phones simply aren't powerful enough to keep up with the game. Maybe we can reduce the fidelity of the art (fewer polygons in models, fewer pixels in textures, etc), but that only goes so far. Most of the game would need to be rewritten in order to be optimized enough for a phone to run it. We did try it, but we only got about 0.5 frames per second. Obviously, not playable.

2) Input. The entire user interface was designed around using a mouse, and part of the game depends on knowing where the mouse is at any given time. Our entire input mechanism would have to be rewritten in order for the game to still work without knowing where the mouse is, and translating various "touch" actions on the screen into "mouse" actions to get the same functionality. Like user3797758 mentioned in their answer, this will require stuff to be rewritten so that "mouse" and "touch" inputs can be fed into the same system, and a bug in one won't affect the other, and a fix of that bug also won't affect the other. This requires more resources to do than my team has available at the moment.

Also mentioned in user3797758's answer, we don't even have Linux support because one of our packages crashes on Linux machines, but works on Windows/Mac. Just because the engine is cross platform doesn't mean everything using it is.

# Answer
> -2 votes
Like someone already mentioned above, it can be all about a cost of testing and quality control for such games. More platforms - always mean and cause more testings your separate QA team should accomplish before dev team can publish such game, especially if we're talking about not so big projects like any of indie game. You also should keep in mind, that every detail of user interface also should be tested by QA workers, even before you will publish it to beta testing for first open player testings.

---
Tags: software-engineering, cross-platform, marketing
---


title: Unity: How to work with forms

text:
# Question
Title: Unity: How to work with forms
Today I learned some cool tricks about sizing containers and its children, I mainly using this, because I need to build some forms.

But now... It is some preffered way how to handle forms? Or some unity component? I imagine something like get values of all InputFields, when the button is clicked.

Originaly I had script, which cycled through all children of container, registered them and I could from the script call method to get values in array. But now I have input fields in the more complex structure, for using of unity scripts for sizing and placement, so the cycle is now not so easy.

So, does unity have some script, or there is some unified way how to do this? How do you handle the forms? And of course, the biggest question, how do you handle standard behaviour as tabing through input fields and submit all on enter press?

# Answer
So, thanks to @Kevin I have approached to custom solution, which I think is the best for me now. I have created FormBehaviour script, which I am linking to Form Container Game Object, where I have the array of inputs, and object for submit and cancel button (all assagnable from editor). And of course submit event, assignable.

Also the Tab navigation is less easier solved, on tab select I find in EventSystem, if is there selected game object and found next or previous selectable.

Here's my Behaviour code.

**EDIT:** the TabSelectable should be seperated to some custom script, for the scene. Especially when I will have more forms in one screen.

```
[Serializable]
public class SubmitForm : UnityEvent<GameObject, IDictionary<string, string>>
{
}

public class FormBehaviour : MonoBehaviour
{
    public SubmitForm OnSubmit;
    public GameObject[] Inputs;
    public GameObject SubmitButton;
    public GameObject CancelButton;

    private readonly IDictionary<string, string> _values = new Dictionary<string, string>();
    private EventSystem _eventSystem;

    public void Start()
    {
        if (SubmitButton == null) throw new InvalidOperationException("The SubmitButton is not set.");

        _eventSystem = EventSystem.current;
        SubmitButton.GetComponent<Button>()
            .onClick
            .AddListener(Submit);

        if (CancelButton != null)
        {
            // Add cancel listener
        }

        BindInputEvents();
    }

    public void Update()
    {
        if (Input.GetButtonUp("Submit") && gameObject.activeSelf)
        {
            Submit();
        }

        TabSelectable();
    }

    public void Submit()
    {
        OnSubmit.Invoke(gameObject, _values);
    }

    private void BindInputEvents()
    {
        foreach (var input in Inputs)
        {
            var inputField = input.GetComponent<TMP_InputField>();
            if (inputField == null) continue;

            _values.Add(input.name, "");
            inputField.onValueChanged.AddListener(value =>
            {
                _values[input.name] = value;
            });
        }
    }

    private void TabSelectable()
    {
        if (!Input.GetKeyUp(KeyCode.Tab)) return;

        Selectable element;
        // Tab to previous element.
        if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift))
        {
            element = GetCurrentSelectable().FindSelectableOnUp();
        }
        // Tab to next element.
        else
        {
            element = GetCurrentSelectable().FindSelectableOnDown();
        }

        if(element != null) element.Select();
    }

    private Selectable GetCurrentSelectable()
    {
        return _eventSystem.currentSelectedGameObject.GetComponent<Selectable>();
    }
}

```
> 0 votes

# Answer
Usually I just create a class for that specific form. Using your example login dialog above, that might look something like this:

```
[System.Serializable] public class LoginDialogEvent : UnityEvent<string, string> {}

public class LoginDialog : MonoBehaviour {
    [SerializeField] private InputField username;
    [SerializeField] private InputField password;
    [SerializeField] private LoginDialogEvent submitEvent = new LoginDialogEvent();
    public LoginDialogEvent SubmitEvent => submitEvent;

    public string Username { get => username.text; set => username.text = value; }
    public string Password { get => password.text; set => password.text = value; }

    void Start() {
        Assert.IsNotNull(username);
        Assert.IsNotNull(password);
    }

    //call this from the click event on the button in the inspector
    public void Submit() {
        submitEvent.Invoke(Username, Password);
    }
}

```

Then you'd use it something like this:

```
LoginDialog dialog = Instantiate(loginDialogPrefab);
dialog.SubmitEvent.AddListener(OnLoginDialogSubmit);
void OnLoginDialogSubmit(string username, string password) {
    loginService.Login(username, password);
}

```

If your application has a limited number of forms, it doesn't take very long to write up the custom classes for them. If you're going to have a huge number of forms, highly complex forms, or forms that are dynamically generated at runtime, you may need something more sophisticated.
> 1 votes

---
Tags: unity, gui, ui-design, game-component, user-interface
---


# Question
Title: How do I draw my particles when an enemy is killed?
I have enemies that move left and right. I was wonder how I could make my particles show up when the enemy is killed?

Here is my particle class

```
    class explode:

        def __init__(self,x,y,height,width,color):
            self.x = x
            self.y = y
            self.height = height
            self.width = width
            self.explode = [
            pygame.image.load("spark_01.png"),
            pygame.image.load("spark_02.png"),
            pygame.image.load("spark_03.png"),
            pygame.image.load("spark_04.png"),
            pygame.image.load("spark_05.png"),
            pygame.image.load("spark_06.png"),
            pygame.image.load("spark_07.png")]

            self.explode = [pygame.transform.scale(image,(image.get_width()//7,image.get_height()//7)) for image in self.explode]

            self.rect = pygame.Rect(x,y,height,width)
            self.direction = "blobright"
            self.anim_index = 0
        def draw(self):

            self.rect.topleft = (self.x,self.y)
            if self.direction == "blobright":
                window.blit(self.explode[self.anim_index], self.rect)
                self.anim_index += 1
                if self.anim_index == len(self.explode):
                    self.anim_index = 0

    black = (0,0,0)
    explode1 = explode(400,450,50,50,black)
    explodes = [explode1]

```

This is where I delete my enemies when they are killed. How can I add my particles after it's deleted and remove the particles afterward?

```

        #--------------------------------------------------------------------------------------------------------- enemys

                # enemys 2
            for enemys in enemying:
                for bullet in bullets:
                    if bullet.rect.colliderect(enemys.hitbox):
                        if enemys.health > -4:
                            enemys.health -= 1
                            minusenemyhealthtext()
                            bullets.pop(bullets.index(bullet))
                        else:
                            enemyscore += 1
                            del enemying[one]
                            enemyors = font.render("" + str(enemyscore), True, (0,0,0))
                            enemydors.center = ((130,125))

```

# Answer
What I've done is add a delete method to the Enemy class, in this method you will create the explosion using the enemy's position, and call it just before deleting the enemy.
> 0 votes

---
Tags: python, pygame
---


title: EventSystem.current is null

text:
# Question
Title: EventSystem.current is null
```
private void OnEnable()
{
    Debug.Log(EventSystem.current);
    EventSystem.current.SetSelectedGameObject(gameObject);
}

```

Very simple script for selecting a UI element on enable. However, EventSystem.current prints null to the console.

Unity 2019.3.15f1

I have an Rewired event system in the scene.

Also tried putting this in an IEnumerator and waiting a frame before logging to the console - no change.

# Answer
> 1 votes
The problem is that `Rewired Event System` does not set `EventSystem.current`. This component allows for multiple independent UIs. Thus, you create multiple `Rewired Event System`s, which of them should be set to `EventSystem.current`?

According to documentation

> Rewired also comes with the RewiredEventSystem component which has the additional option to allow multiple Event Systems to run in the scene at the same time. This can be useful if you want to create multiple independent UI's for different Players.

Now, to solve your problem, you should not use `Rewired Event System` but instead create normal `Event System` and replace `Standalone Input Module` with `Rewired Standalone Input Module`.

According to documentation

> You can either create a normal Unity Event System and replace the Standalone Input Module with the Rewired Standalone Input Module component or you can create a Rewired Event System from either of the menu items:
>
> * GameObject -\> Create Other -\> Rewired -\> UI -\> Rewired Event System
> * Window -\> Rewired -\> Create -\> UI -\> Rewired Event System

---
Tags: unity
---


# Question
Title: What is the fastest way to work out 2D bounding box intersection?
Assume that each Box object has the properties x, y, width, height and have their origin at their center, and that neither the objects nor the bounding boxes rotate.

# Answer
(C-ish pseudocode - adapt language optimizations as appropriate)

Code for coordinate system centered on bounding boxes

```
bool DoBoxesIntersect(Box a, Box b) {
  return (abs(a.x - b.x) * 2 < (a.width + b.width)) &&
         (abs(a.y - b.y) * 2 < (a.height + b.height));
}

```

Code for coordinate system using top-left coodinates on bounding boxes

```
bool DoBoxesIntersect(Box a, Box b) {
  return (abs((a.x + a.width/2) - (b.x + b.width/2)) * 2 < (a.width + b.width)) &&
         (abs((a.y + a.height/2) - (b.y + b.height/2)) * 2 < (a.height + b.height));
}

```

In English: On each axis, check to see if the centers of the boxes are close enough that they'll intersect. If they intersect on both axes, then the boxes intersect. If they don't, then they don't.

You can change the \<'s to \<= if you want to count edge-touching as intersecting. If you want a specific edge-touch-only formula, you can't use == - that will tell you if the corners touch, not if the edges touch. You'd want to do something logically equivalent to `return DoBoxesIntersectOrTouch(a, b) && !DoBoxesIntersect(a, b)`.

It's worth mentioning that you can get a small but significant speed increase by storing the half-width and half-height in addition to (or instead of) the full width and full height. On the other hand, it's rare for 2d bounding box intersection to be the performance bottleneck.
> 61 votes

# Answer
This works for two rectangles aligned with the X and Y axis.
Each rectangle has the properties:
"left", the x coordinate of its left side,
"top", the y coordinate of its top side,
"right", the x coordinate of its right side,
"bottom", the y coordinate of its bottom side,

```
function IntersectRect(r1:Rectangle, r2:Rectangle):Boolean {
    return !(r2.left > r1.right
        || r2.right < r1.left
        || r2.top > r1.bottom
        || r2.bottom < r1.top);
}

```

Note that this is designed for a coordinate system in which the +y axis points **down** and the +x axis is directed to the right (i.e. typical screen/pixel coordinates). To adapt this to a typical cartesian system in which +y is directed upward, the comparisons along the vertical axes would be reversed, e.g.:

```
return !(r2.left > r1.right
    || r2.right < r1.left
    || r2.top < r1.bottom
    || r2.bottom > r1.top);

```

The idea is to capture all possible conditions upon which the rectangles will *not* overlap, and then negate the answer to see if they *are* overlapped. Regardless of the direction of the axes, it's easy to see that two rectangles will *not* overlap if:

* the left edge of r2 is further right than the right edge of r1

```
 ________     ________
|        |   |        |
|   r1   |   |   r2   |
|        |   |        |
|________|   |________|

```
* *or* the right edge of r2 is further left than the left edge of r1

```
 ________     ________
|        |   |        |
|   r2   |   |   r1   |
|        |   |        |
|________|   |________|

```
* *or* the top edge of r2 is below the bottom edge of r1

```
 ________
|        |
|   r1   |
|        |
|________|
 ________
|        |
|   r2   |
|        |
|________|

```
* *or* the bottom edge of r2 is above the top edge of r1

```
 ________
|        |
|   r2   |
|        |
|________|
 ________
|        |
|   r1   |
|        |
|________|

```

The original function - and an alternative description of why it works - can be found here: http://tekpool.wordpress.com/2006/10/11/rectangle-intersection-determine-if-two-given-rectangles-intersect-each-other-or-not/
> 52 votes

# Answer
If you want object-aligned bounding boxes, try this tutorial on the **seperation axis theorem** by metanet: http://www.metanetsoftware.com/technique/tutorialA.html

SAT isn't the fastest solution, but it's relatively simple. You're trying to find a single line (or a plane if 3D) that will seperate your objects. If this line exists it's guarenteed to be paralell to the edge of one of your boxes, so you iterate through all edges testing to see if it seperates the boxes.

This also works for axis-aligned boxes by constraining to just the x/y axis.
> 12 votes

# Answer
Lot of math here for a very simple problem, assume that we have 4 points determined for a rect, top, left, bottom, right...

In the case of determining whether 2 rects collide we need only look that all possible extremes that would prevent collisions, if none of these are met, then the 2 rects MUST collide, if you want to include boundary collisions, simply replace the \> and \< with appropriate \>= and =\<.

```
struct aRect{
  float top;
  float left;
  float bottom;
  float right;
};

bool rectCollision(rect a, rect b)
{
  return ! ( b.left > a.right || b.right < a.left || b.top < a.bottom || b.bottom > a.top);
}

```
> 9 votes

# Answer
The DoBoxesIntersect above is a good pairwise solution. However, if you have a lot of boxes, you still have an O(N^2) problem, and you might find you need to do something on top of that like what Kaj refers to. (In the 3D collision detection literature, this is known as having both a broad-phase and a narrow-phase algorithm. We'll do something really fast to find all possible pairs of overlaps, and then something more expensive to see if our possible pairs are actual pairs.)

The broad-phase algorithm I've used before is "sweep-and-prune"; for 2D, you'd maintain two sorted lists of the start and end of each box. As long as box movement is not \>\> box scale from frame to frame, the order of these lists isn't going to change much, and so you can use bubble or insertion sort to maintain it. The book "Real-Time Rendering" has a nice writeup on optimizations you can do, but it boils down to O(N+K) time in the broad phase, for N boxes, K of which overlap, and with excellent real-world performance if you can afford N^2 booleans to keep track of which pairs of boxes are intersecting from frame-to-frame. You then have O(N+K^2) time overall, which is \<\< O(N^2) if you have many boxes but only a few overlaps.
> 5 votes

# Answer
Alternate version of ZorbaTHut's answer:

```
bool DoBoxesIntersect(Box a, Box b) {
     return (abs(a.x - b.x) < (a.width + b.width) / 2) &&
     (abs(a.y - b.y) < (a.height + b.height) / 2);
}

```
> 3 votes

# Answer
The fastest way is combine all 4 values in a single vector register.

Store the boxes in a vector with following values `[ min.x, min.y, -max.x, -max.y ]`. If you store boxes like this, the intersection test only takes 3 CPU instructions:

`_mm_shuffle_ps` to reorder the second box flipping min and max halves.

`_mm_xor_ps` with magic number `_mm_set1_ps(-0.0f)` to flip signs of all 4 values in the second box.

`_mm_cmple_ps` to compare all 4 values with each other, comparing following two registers:

```
[ a.min.x, a.min.y, -a.max.x, -a.max.y ] < [ b.max.x, b.max.y, -b.min.x, -b.min.y ]

```

Finally, if needed, `_mm_movemask_ps` to get the result out of vector unit into a scalar register. Value 0 means the boxes intersected. Or if you have more than 2 boxes this is not needed, leave the values in vector registers and use bitwise operations to combine results from multiple boxes.

You have not specified language nor platform, but the support for SIMD like this, or very similar, is available in all platform and languages. On mobile, ARM has NEON SIMD with very similar stuff. .NET has Vector128 in System.Runtime.Intrinsics namespace, and so on.
> 3 votes

# Answer
Depending on the problem you try to solve you might be better off keeping track of your object while you move them, ie, keep a list of sorted x start and end positions and one for start and end y positions. If you have to do a LOT of overlap checks and therefore need to optimize, you can use this to your advantage, as you can immediately look up who is ending closes to your left, everyone who's ending is to the left of that can be pruned immediately. Same apply for top, bottom and right.
The bookkeeping costs time of course, so it's more suited for a situation with few moving objects but lots of overlap checks.
Another optionh is spatial hashing, where you bucket the objects based on approximate position (size might put em in multiple buckets), but there again, only if there's a lot of objects, with relatively few of them moving per iteration due to bookkeeping cost.
Basically anything that avoids (n\*n)/2 (if you check object a against b you won't have to check b against a obviously) helps more than optimizing bounding box checks. If bounding box checks are a bottleneck, I'd seriously advise to look into alternative solutions to the problem.
> 2 votes

# Answer
The distance between centers is not the same as the distance between corners (when one box is inside the other for instance), so IN GENERAL, this solution is the correct one (me thinks).

distance between centers (for, say, x): `abs(x1+1/2*w1 - x2+1/2*w2)` or `1/2 * abs(2*(x1-x2)+(w1-w2)`

Minimum distance is `1/2 w1 + 1/2 w2 or 1/2 (w1+w2)`. the halves cancel so..

```
return
ABS(2*(x1 - x2) + (w1-w2) ) < (w1+w2)) &&
ABS(2*(y1 - y2) + (h1-h2) ) < (h1+h2));

```
> 2 votes

# Answer
The term that you are looking for is AABB bounding boxes. If you look at https://developer.mozilla.org/en-US/docs/Games/Techniques/3D\_collision\_detection you will see a few examples for intersection testing. The particular code for this is:

```
function intersect(a, b) {
  return (a.minX <= b.maxX && a.maxX >= b.minX) &&
         (a.minY <= b.maxY && a.maxY >= b.minY);
}

```

I cannot comment on results in this community yet, but one highly rated answer from @Ponkadoodle is not correct. See below test that shows intersecting rectangles that the algorithm would not detect correctly:

```
// THIS DOES NOT WORK, its a test to show a false-negative detection.

const r1 = {
  left: 100,
  right: 200,
  top: 200,
  bottom: 300
};

const r2 = {
  left: 101,
  right: 199,
  top: 51,
  bottom: 201
}

let result = !(r2.left > r1.right
    || r2.right < r1.left
    || r2.top < r1.bottom
    || r2.bottom > r1.top);

console.log(`Intersects? ${result}`);
```
> 2 votes

# Answer
Here's my implementation in Java **assuming a twos-complement architecture**. If you're not on twos-complement, use a standard *Math.abs* function call instead:

```
boolean intersects(IntAxisAlignedBox left, IntAxisAlignedBox right) {
    return
        (
            lineDeltaFactor(left.min.x, left.max.x, right.min.x, right.max.x) |
            lineDeltaFactor(left.min.y, left.max.y, right.min.y, right.max.y) |
            lineDeltaFactor(left.min.z, left.max.z, right.min.z, right.max.z)
        ) == 0;
}

int lineDeltaFactor(int leftMin, int leftMax, int rightMin, int rightMax) {
    final int
            leftWidth = leftMax - leftMin,
            rightWidth = rightMax - rightMin,

            leftMid = leftMin + ((leftMax - leftMin) >> 1),
            rightMid = rightMin + ((rightMax - rightMin) >> 1);

    return (abs(leftMid - rightMid) << 1) / (leftWidth + rightWidth + 1);
}

int abs(int value) {
    final int mask = value >> (Integer.SIZE - 1);

    value ^= mask;
    value += mask & 1;
    return value;
}

```

Assuming a half-decent compiler / LLVM inline expands these functions to avoid expensive stack juggling and v-table look-ups. This **will fail** for input values that are close to 32-bit extremes (i.e. `Integer.MAX_VALUE` and `Integer.MIN_VALUE`).
> 1 votes

# Answer
```
struct Rectangle
{
  //top left corner
   float ax;
   float ay;

 //bottom right corner
   float bx;
   float by;
};

bool collision(Rectangle A, Rectangle B)
{
  if(A.bx >= B.ax && A.ax <= B.bx && A.ay >= B.by && A.by <= B.ay)
  {
    return true;
  }
  else
  {
   return false
  }
}

```

I'm pretty sure this is the simplest form of box to box collision detection. You only need the position of two corners on diagonally opposite ends of the rectangle to perform the check.
> 0 votes

---
Tags: collision-detection, optimization, bounding-boxes
---


# Question
Title: How to make this C++ game server cross platform? [Focusing on Ubuntu compatibility right now]
**The question's description will evolve depending on requested information or evolution of answers.**

I made this C++ server for a game, which works on Windows, and would like to **make it cross-platform, so it at least works on Linux (Ubuntu), macOS would be a plus** i'd really appreciate, but not indispensably necessary (specially if single "cross-platform executable" isn't a possibility).

The server was programmed using VisualStudio IDE. These are all my source files I copied to another directory, including a custom static library (this one is in the same directory, the rest are all in C:/libraries):

Project dependencies are the following as configured in VisualStudio:

All libraries are to be linked statically. These are the ones my server uses:

* GLM: Header only, cross platform.
* Cereal: Header only, cross platform.
* SFML modules: Can be linked statically. Cross platform according to them, even though this surprises me, since, for example, sfml\_network module depends on winsock, which is a windows library...
* MORPH\_Shared\_functions, My own library: Is static. It's own dependencies are the same as already listed for server, so I'm asuming that would make it cross-platform.

The entire server fits in a single executable without dynamic library dependencies. I tried moving the exe to another computer, and it works fine without the libraries installed in the system since they're merged into the executable.

**According to the first answer I got, Every platform should be considered separately. So I'm focusing on Linux/Ubuntu first:**

**\- Progress 1:**

Begining with Ubuntu, I tried the g++ compiler for windows. I installed it on windows by installing MinGW, and now I can use it from windows's cmd. I tried following this nice and simple guide: https://courses.cs.washington.edu/courses/cse373/99au/unix/g++.html

From what I read, I understand a propper approach would be first compiling each .cpp individually, so I made myself a list of commands:

```
g++ -c -o Game.o Game.cpp
g++ -c -o CommandManager.o CommandManager.cpp
g++ -c -o ServerPlayer.o ServerPlayer.cpp
g++ -c -o ServerProp.o ServerProp.cpp
g++ -c -o ServerWorldState.o ServerWorldState.cpp
g++ -c -o UDP_Server_CS.o UDP_Server_CS.cpp

```

then I would do something like:

```
g++
-Wall
-o MORPH_Server
-Xpreprocessor SFML_STATIC
-I MORPH_Shared_Functions
-I C:\libraries\SFML\SFML-2.5.1\include
-I C:\libraries\GLM\glm
-I C:\libraries\CEREAL
-L C:\libraries\SFML\SFML-2.5.1\extlibs\libs-msvc\x64
-L C:\libraries\SFML\SFMLx64SourceAndCompile\lib\Debug
-l MORPH_Shared_Functions.lib
-l winmm.lib
-l ws2_32.lib
-l sfml-system-s-d.lib
-l sfml-network-s-d.lib
Main.o Game.o CommandManager.o ServerPlayer.o ServerProp.o ServerWorldState.o
UDP_Server_CS.o

```

In order to link them all together

However, the first individual module compilation attempt (Game.cpp) results in a header from my custom shared library not being found with error:

```
In file included from Game.h:2:0,
                 from Game.cpp:1:
UDP_Server_CS.h:1:33: fatal error: udp_network_manager.h: No such file or
directory
 #include "udp_network_manager.h"

```

I really don't know if I should link all libraries for each compiled module, so for now I at least tried:

```
g++ -c -o Game.o -lMORPH_Shared_Functions.lib Game.cpp

```

In order to point to my shared library, hopefully helping with pointing to it's header, but this returns the same error.

I imagine if I continued with this approach (which works for ubuntu, and no other OS's I know of), I'd first try to get the commands right for compiling, and then I could try making visual studio compile with CMake using that same commands, or something like that. I don't know too much about cmake, I only used it for compiling some libraries like sfml a few times.

**Note:** I already did a similar question some weeks ago (How to remotely host my c++ game server on Ubuntu?). This one is based on the same objective, but with more specifics on the case, and some actual strategies already developed. In general I'm still looking for advice, ideas, and even specific guides.

# Answer
As someone with some cross-platform experience, my advice would be to put everything aside for 1 or 2 days and start learning the basics of CMake. CMake is a cross-platform build system generator that performs a lot of tedious tasks for you like finding your libraries, sorting out dependencies (to some degree) and setting up the compiler and linker. Once you have wrapped your program into a CMake structure, you can generate Visual Studio project files or Linux Makefiles automatically and all that remains is to call the corresponding build command (`make`, `ninja`, etc.) - assuming all dependencies are found.

You can also include other CMake projects into your own project so that they get built together. Don't know if there is a general description for that, but in the Google Test documentation they describe several ways to include their library to other CMake projects. Guess that does work for other libraries like SFML too. Of course, you can also build SFML separately, install it and then let CMake find it.

> According to the first answer I got, Every platform should be considered separately.

The advantage of using CMake would be that most of the platform-specific setup is done by it. As long as all your libraries are cross-platform and can be found by CMake (if not, you have to point it to the directory), there is not much else to do for you.

So here is how I think you should approach this:

* learn (modern) CMake
* wrap your project into a CMake structure
* get it running on Windows first! Generate the projects build files with CMake and compile them from the command line, not from VisualStudio
* Once it runs, try to do the same with Linux and/or Mac

The reason why you should start with Windows is that you got everything already set up and know that it can be built in the current environment. The reason why I suggest avoiding Visual Studio with CMake is that this adds another layer where something can go wrong. Focus on getting a working CMake build on Windows. Once that is achieved you can try to integrate it into VS.

As soon as is runs on Windows, getting it to run on Linux/Ubuntu should be a lot easier. Just install all your dependencies (`sudo apt-get install INSERT_DEPENDENCIES`, build and install SFML) and CMake will usually find them automatically.

**Some further remarks**

Take your time with CMake and especially look for tutorials on **modern** "target-based" CMake approaches. This link should give you an overview of what modern CMake is about. You probably need to read some material before if you want to understand what he is talking about. However, if you follow these guidelines writing cross-platform code gets as easy as it can be.

If you are using GitHub and once you get everything running, you might also think about adding some GitHub actions to your repository that build your library on all supported systems with all supported compilers every time you make a commit. This will give you early feedback if the new code does break cross-platform compatibility. Gitlab has something similar, but I don't know how it is called there. ;)

> SFML modules: Can be linked statically. Cross platform according to them, even though this surprises me, since, for example, sfml\_network module depends on winsock, which is a windows library...

It only depends on Winsock in windows. They most certainly have written platform-specific code with its own dependencies for every supported operating system. So on Ubuntu, you will have a Linux specific dependency instead.
> 0 votes

---
Tags: c++, cross-platform, linux
---


title: Collisions and Colliders

text:
# Question
Title: Collisions and Colliders
Does anyone know how to prevent a gameobject from colliding with another gameobject but can still register collisions? Like a ball that can bounce off of the wall or ground and can pass through the player himself.

What I have tried: Creating two Colliders on the ball(which has a rigidbody component) and making one of them bigger than the other (and turn on "Is Trigger" on the bigger collider). Then write code in the OnTriggerEnter and the OnTriggerExit functions to disable/enable the smaller collider so that the ball could fly right through the player. But that is completely useless when the ball is not in motion and the player walks over it(because it'll fall straight down through the ground).

# Answer
> 2 votes
You can configure the layer collision matrix in the Physics settings of your project so your gameobject in a particular layer interacts or not with other layers

You can find it in Edit \> Project Settings \> Physics

---
Tags: unity, c#, collision-detection, physics, rigidbody
---


# Question
Title: My lighting stays the same when I go indoors?
My problem can be seen here notice how the shadows don't change intensity or color when moving indoors to the cave. The only thing that changes is the highlights when I move under the directional light. I was thinking about adding global illumination but I don't think that would work with a toon shader. How can I get my lighting to become darker once I enter indoors e.g a cave. Thanks!

# Answer
> 1 votes
One solution is to setup light probes so your dynamic objects receive bounced light information from the static environment.

As explained in the manual: Light Probes for moving objects.

---
Tags: shaders, lighting, cel-shading
---