# Question
Title: Twin-stick controls for a cohesive group of agents
I'm trying to implement a classic twin-stick controller for a group of physics-based game objects. Here are the rules I'm trying to follow:

* Agents **always** stay close to each other within a certain threshold.
* Moving the left stick moves the entire group in that direction.
* Moving the group on a collider like a wall will "compress" the group like a ball. Releasing the left stick will make the group recover its "natural" shape.

I tried a few things:

* Classic steering with cohesion/follow behaviors: This kinda works, but when moving against a sharp corner, a part of the group will move on and separate from the others. Adjusting the steering weights in this scenario produces unnatural results, and the whole thing just feels too "floaty".
* Softbody simulation: This works pretty well when moving on a corner, but you can really feel the springs between each agent. Again, it just feels wrong as a whole.
* Box2D joints between each agent: Keeps all the agents tightly packed, but the group feels very rigid.

The solution might be a combination of the previous points, but I'm pretty sure I'm over-thinking this.

# Answer
Use a combination of **both** soft body and classic steering.

Use a soft body grid (or similar) to figure out the **ideal target** placement of the agents then have the agents independently **try** to get to their respective positions within some random organic fuzziness to make it look less perfect/artificial.

The agents may optionally give up if they get too far or can't find a way and bump each other into swapping positions if they're out of order.

With some tweaking (depending on your subjective goal) this should get you to an acceptable movement that fills your requirements.
> 1 votes

# Answer
flocking with independent behavior based on situation, where part of that behavior is broadcast message and part is cascade to nearest neighbor that then informs rest of individuals in the unit.

That way if an order to lose formation is given, 5 feet between men, it broadcasts to rest of unit. If close formation is ordered it broadcast also. That order would not be cascaded by weight by iteration but only set at if based on formation by broadcast.

while if a wall impact created a cascade order procedure, it would be weighted cascade and a move for each unit and move of 'unit center point' that would include positional effect by number of iteration it takes to get the message.

The method to cascade I developed in an app years ago, everyone cascades to neighbor but ignores 'order number 'something'' if it already processed that order, and distance adds to weight of order in cases where you want a smooth transition.(to stop recursion orders are numbered and processed only once per individual)

so if one guy hits wall, he cascades 'move closer' formation message to neighbors, and as it filters outwards, they all cascades to neighbors but only first message reception is processed and is processed by depth of iteration to lessen the effect as further from source.

And each unit has a center point at middle of formation that then deduces there path to best choice location individually while the entire unit is pathed with that center point.

Also can be useful in things like individual morale cascading to other units,awareness or agro cascading, or healing cascading to units with effect that effectively includes distance from first effected unit. It also can be used to determine if a unit needs to change formation to a line for instance when it can not 'closer' and fit through an area. A formation change would be created instead of a modification to location within a formation.

Each formation has a center point, and each individual has a dfcp (distance from center point) for the formation(no situation) and a dfcp modification value based on situation where any individual encounter a collision or event. Then units path to that modified location and it changes when any unit collides or stops colliding. The (no situation) values are set by the units choice of formation. And the entire unit is moved by pathing the center point, while each unit paths based on there dfcp offset of that center point.

It is possible to use broadcast all in non weighted events, but the 8 neighbor broadcast method allows for different depths based on iteration count.

Although that code was stolen from me years ago and I have not been compensated.

think of this as explanation of center point, and shadow as broadcast and cascade pipes to neighbors. You only have to walk the center point, while the individuals calculate distance from that center point, and entire unit will still react to events effecting unit on other side of formation while still maintaining independent actions.

Green Day - Boulevard of Broken Dreams https://www.youtube.com/watch?v=Soa3gO7tL-c

And cascade can also be used to fill front line ranks if units are damaged, routed or killed.

thinking back on the original design I wrote, some of the other uses is that a single independent unit, can get full unit status by what messages it receives from different individuals through the cascade or broadcast, and can be used to get healers to start casting group heals, or generals to call in back up cavalry, or various other full unit actions based on individual states within the unit.

So while setting position and agro, the healer unit is also receiving detailed information of damage and morale information from each unit as the individual units broadcast or cascade state.

And the general unit is paying attention to the states of individuals damage and morale, and can order front line rotations after collision with enemy in combat and some distress situation from a morale or damage cascade or broadcast.

Any message that should inform every unit equally is full broadcast, any message that should have a distance component is cascaded.

cascade messaging is also shown in this movie, although you would have to know about glyphs in the sand. https://www.youtube.com/watch?v=mdT163r3dUQ
> 0 votes

---
Tags: physics, control
---


# Question
Title: I'm Dragging object by using touch (mobile) it doesn't stop when hit collider
I want to make object stopped when it hit collider of another object.
But it doesn't stop. How can I fix this? *\- Unity*

**my code is:**

```
public class move: MonoBehaviour {
    public float speed = 0.5f;
    // Update is called once per frame
    void Update () {
      if (Input.touchCount ==1)
        {
            Touch touch = Input.GetTouch(0);
            float x = -7.5f + 15 * touch.position.x / Screen.width;
            float y = -2;
            transform.position = new Vector2(x * speed, y);
        }
    }
}

```

# Answer
The easiest approach would be: "store the object's old position, update its position, if it is colliding, move it back."
Sadly, in Unity, you cannot determine directly whether or not a collision is happening *at the moment*. One could implement OnCollisionEnter / OnCollisionExit to set some "colliding" state, but you would need to be careful with synchronisation between moving / checking collision.
> 0 votes

---
Tags: unity, c#, game-design, mobile, touch
---


# Question
Title: I am having this error in unity and i don't know what's causing it
I don't know how it happen this is an endless runner game The road is 15 on x and 100 on z. This is happening in android road is a cube with png image as texture it is distorted and turn blue every 2 sec.

# Answer
Well the question is not clear but since you are talking about the road I'm 100% sure it's about the blurriness of the texture so you have 2 solution.

1. First go in Quality setting change Anisotropic Filtering from Disable to PerTexture and select your texture change Filter Mode to Trilinear and set the aniso level all the way up
2. You second choice is to go in Quality setting again change Anisotropic Filtering to ForcedOn.

This will get rid of the blurriness of the road texture but note that texture Filtering can take some CPU resources. Hope this will help
> 1 votes

---
Tags: unity
---


# Question
Title: How can I use ImGui to render simple text instead of using stb_truetype directly?
Since ImGui builds on top of stb\_truetype for its font rendering, I thought it could be nicer to use its already built font-processing capabilities (`ImGui::GetIO().Fonts`), and render with those, instead of using `stb_truetype` directly.

However, I've been having trouble figuring out how to do this, specifically how to get quad position/texture coordinates for a given string to use with the preloaded texture at `ImGui::GetIO().Fonts->TexID`.

I'm not looking to draw buttons/text inside ImGui windows, all I want to do is to use ImGui to build vertex data for a given string so that I can render it anywhere.

# Answer
From the GitHub issue you opened and the ImgUi FAQ:

Create a dummy window with `NoTitleBar|NoResize|NoMove|NoScrollbar|NoSavedSettings|NoInputs`, then you can retrieve the `ImDrawList*` via `GetWindowDrawList()` and draw to it in any way you like.
> 3 votes

---
Tags: opengl, textures, fonts, text
---


# Question
Title: Simple determining starting experience and to next lvl experience for RPG
I'm a very simple minded person and don't understand how algebraic functions translate into programming, but I'm trying to create a simple lvling system.

In previous threads I read equasions like "level = etc etc...", but instead what's happening is you're selecting the starting lvl of the character you create in an rpg database manager. What's needed then are startingExp and toNextLvl.

So what I've figured out so far (to do this in the simplest form) is:

```
int startingExp = 0;
for (int x = 0; x < selectedLvl; x++) {
    startingExp += 100 * x;
}

```

Then:

```
int toNextLvl = startingExp + (selectedLvl * 100);

```

It's just a start, but I'm wondering if this is a valid way of going about it? I didn't want to use Math.Log as it takes and outputs doubles, and when people are posting their equasions I'm very confused as how I would translate y = (x ^ 2) into starting exp and starting toNextLvl exp...

# Answer
> 0 votes
The particular leveling formula you've written is equivalent to:

```
const int XP_INCREMENT_PER_LEVEL = 100;

int TotalXPToReachLevel(int level) {
   return XP_INCREMENT_PER_LEVEL * level * (level + 1) / 2;
}

```

It's a quadratic, rather than exponential growth.

I got this using the formula for triangular numbers, the sum of the first n natural numbers, by noticing that your XP targets go up like this:

$$100 + 200 + 300 + 400 + ... +level \cdot 100 = 100 \cdot \left(1 + 2 + 3 + 4 + ... + level\right)$$

Doing this with your for loop is perfectly valid too, if you find that code clearer. You could probably do several thousand iterations through that tiny loop without seeing a meaningful performance impact in the kinds of scenarios where you need to calculate an XP target.

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


# Question
Title: Converting a quaternion in a right to left handed coordinate system
I have a quaternion from an IMU that id like to represent in unity. The issue is that the sensor uses a right handed coordinate system while unity uses a left handed coordinate system. In order to have the rotations of the IMU reflect in unity correctly, I would need to remap the axis. How can I do this by altering the quaternion components?

Specifically, I would need to map

```
         sensor   unity
forward  x        z
up       z        y
right    -y       x

```

I have seen multiple questions regarding this question especially this one.

Convert quaternion to a different coordinate system

However, it only explains a specific case where its a right hand to right hand remapping.

If possible, include an explanation without mathematics equations of how you would map any coordinate system to any other coordinate system.

# Answer
A quaternion can be thought of as an angle-axis representation:

```
quaternion.xyz = sin(angle/2) * axis.xyz
quaternion.w = cos(angle/2)

```

So, converting them between two coordinate systems can be broken down into two steps:

1. Map the axis into the new coordinate system.
2. If changing between left & right hand coordinates (i.e. if there's an odd number of axis negations or axis exchanges between the two), negate the angle.

Since `cos(-angle) = cos(angle)` and `sin(-angle) = -sin(angle)` this is the same as flipping the axis of rotation, negating the x, y, and z parts.

Taking your specific example:

```
         sensor   unity
forward    x        z
up         z        y
right     -y        x

```

To map between these, we need to swap pairs of axes twice (x swaps with z, then y swaps with z) and negate once on y, so that's an odd number of flips, meaning we've changed handedness and will need to negate our angle.

Another way to see this is that if you can take your right hand and point your thumb forward (x), your index finger left (-y), and your middle finger up (z), so this sensor coordinate system is right-handed. To do that with Unity, we'd need to use our left hand to point the thumb right (x), index up (y), and middle forward (z).

We can combine axis remapping and negation steps into:

```
Quaternion ConvertToUnity(Quaternion input) {
    return new Quaternion(
         input.y,   // -(  right = -left  )
        -input.z,   // -(     up =  up     )
        -input.x,   // -(forward =  forward)
         input.w
    );
}

```
> 7 votes

---
Tags: unity, rotation, quaternion
---


title: Determining connectedness of rectangles

text:
# Question
Title: Determining connectedness of rectangles
I am working on some functions to use in my enemy state machines.

I want to write a function which determines whether the platform the enemy is standing on is connected to the platform the player is standing on.

Platforms have associated rectangles, and by *connected*, I mean there is a *chain* of rectangles from the first rectangle to the second rectangle.

Here's an illustration:

Here are my assumptions:

1. The rectangles contain their perimeters.
2. Two rectangles touching only on their perimeter are connected.
3. Two rectangles overlapping are connected.
4. The rectangles are guaranteed to be axis-aligned.
5. The rectangles will be at integer coordinates (the grid is 1x1).
6. Every rectangle has attributes like topleft, bottomright, etc.
7. Directly connected rectangles won't necessarily have any corners in common.

My question: **What is an efficient way to determine the connectedness of rectangles in 2D space?**

---

**NOTE:** I asked a more specific version of this question in a Godot forum, but given that this is a general game dev question, I figured I'd ask this variation here.

# Answer
We can represent connections between platforms using a *graph*. The *nodes* of our graph will represent platforms and the *edges* of our graph will represent direct connections between platforms.

We can represent this graph using an *adjacency matrix*, that is, a matrix whose indices represent our nodes and which uses 0 or 1 to represent whether there's a direct connection between them.

Here's an illustration:

<sup>(Note that platforms are directly connected to themselves.)</sup>

In code, we can use a list of lists to represent this final matrix.

So, to build a model of the direct connections between platforms, we can construct a list of lists in the following way (using pseudo-code):

```
var connection_matrix = []
for platform_1 in platforms:
    var submatrix = []
    for platform_2 in platforms:
        if platform_1.is_directly_connected_to(platform_2):
            submatrix[platform_2] = 1                   # 1 represents an edge on the graph, that is, a connection between platforms
        else:
            submatrix[platform_2] = 0                   # 0 represents absence of an edge, that is, no connection between platforms
        connection_matrix[platform_1] = submatrix

```

The only tricky thing here is constructing the `is_directly_connected_to()` function. You can either use the collision resources built into your engine to determine if two platforms are touching, or, use any number of algorithms for determining it two rectangles intersect.

Once we have this graph of the connections between our platforms, we can use one of many algorithms to determine if a path exist between two nodes in the graph.

---

Alternatively, you can represent the graph using a dictionary-type data structure whose keys are platforms and whose values are lists of platforms, those directly connected to the keys.

Here's an illustration:

Constructing this dictionary representation is easy:

```
var connection_dictionary = []
for platform_1 in platforms:
    var direct_connection_list = []
    for platform_2 in platforms:
        if platform_1.is_directly_connected_to(platform_2):
            direct_connection_list.append(platform_2)
    connection_dictionary[platform_1] = direct_connection_list

```

Once we have this graph of the direct connections between our platforms, we can use the following *depth-first* search algorithm to determine if there's a path between any two nodes in the graph.

```
def find_path(graph, start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if not graph.has_key(start):
        return None
    for node in graph[start]:
        if node not in path:
            newpath = find_path(graph, node, end, path)
            if newpath: return newpath
    return None

```

(This algorithm is from the Python docs, but it can be adapted to other languages.)
> 1 votes

# Answer
Construct a graph of which rectangles are connected using collision detection and do a flood-fill.
> 1 votes

---
Tags: 2d, path-finding
---


# Question
Title: How do open world games handle efficiently enemy respawn?
I'm currently working on a 2D open world game loaded in chunks, initially I thought It would be sufficient to spawn entities randomly in a specific "radius" close to the player, and periodically remove distant enemies.

Though appealing, this system is inefficient unless you keep in memory the chunks surrounding the chunk the player is in (if an enemy needs to spawn on a chunk which is currently not in memory, you have no way of knowing wether you can actually place it in a specific tile or not, since it may be occluded by a wall) which is why I'm currently spawning enemies as soon as chunks are loaded, but there's a problem..

A massive complication arises when enemies are spawned with specific criteria. Assume a little dungeon spawns inside a chunk, it needs 2 enemies and a chest with loot in-between them. When you're done with it, it shouldn't respawn unless an hour passed. You can't just spawn those enemies inside the structure as soon as it's close enough to the player, otherwise you could go back 'n fort, kill the enemies and keep looting the chest's content.

Time to make a cache right? Let's forget for a moment any complication related to how you could make it memory efficient, and analyze this particular scenario:

* The player enters a chunk with said structure
* Enemies and chests are then spawned
* A cache marks this particular dungeon as "already spawned, check back in an hour"
* Instead of getting closer to the dungeon, the player moves in the opposite direction, until the dungeon gets out of view and enemies are removed since they're now too distant
* ..few minutes later, the player goes back where the dungeon is, only to find an empty dungeon because the structure was marked as "already spawned" and wont spawn again unless an hour is passed.

I thought about caching all enemies that where present inside a chunk when it gets out of view and restoring them as soon as the chunk is visible again, yet again this requires caching every entity inside a chunk and keep the entry available for an hour, and periodically check if in that particular chunk an hour is passed and we can spawn again enemies

Doesn't look too bad, but if a player moves in a straight line in my game for an hour I would need to cache about 200 chunks before cache entries start expiring!

Is there a better solution? How do modern games handle enemies spawn? How do they get around these difficulties? I'm particularly interested in knowing how online games do it considering the crazy amount of memory (which should be shared between servers) such systems may require

# Answer
When you need to persist the state of a chunk but you are running out of memory, consider persisting it to the hard drive. If your game has enough complexity and data to warrant it, you might want to consider to use an embedded SQL database like SQLite for this purpose.

However, I doubt that this is even necessary for your game. How much data do you really need to keep in memory for an enemy in an inactive chunk? You don't need to render it, so any visual data (mesh, animation state...) can be unloaded. You don't need to update it, so its AI state is likely irrelevant, too.

So what's left to persist?

Position? 3 floating point numbers. Rotation? Between 1 and 4 floating point numbers, depending on how you handle it. Game mechanical values? A couple integers. I would be surprised if you manage to come over a few hundred bytes per entity. But let's be generous and assume a full KB of data. So one GB of memory could store up to a million inactive entities.
> 2 votes

---
Tags: architecture, design-patterns, memory-efficiency, memory, spawning
---


# Question
Title: Deleting an item in the game world: detecting if an item supports other items
I'm writing a 3D construction module similar to the how you build houses in the Sims. Users are able to build walls and floors (which also act as ceilings) on multiple floors (layers). This question needs a little background info:

I'm not using an physics, there is no gravity. I use the term floor/ceiling tile here interchangeably. Essentially all are floor tiles, ceiling tiles are just floor tiles on a higher layer.

I store the build data in a multi dimensional array like:

```
grid[layer][row][column][position]

```

The *layer* represents the layer (ground floor, 1st floor etc..). The *row* and *columns* make up the grid. The *position* can hold any number of 3 positional values, namely:

* 0 : wall on west side of cell
* 1 : wall on south side of cell
* 2 : ceiling

So for example, a south wall on the row/column 2/4 on layer 3 would looks like:

```
grid[3][2][4][0=>null,1=>item,2=>null]

```

This works great, and it's easy to write functionality to check if a item can be placed at any position (by looking at neighbouring cells, layers below etc...)

**Here is the actual problem and question:**

I'm writing functionality to delete items within the game world. The rules by which I decide if something can be deleted are what you would expect in real life:

* Any item that's not on the ground floor needs something else supporting it

So for the following examples:

Only 1 of the 2 blue tiles adjacent to the red tile could be deleted

The red tile cannot be deleted because the wall connected to it would no longer have a support.

Walls are simple enough, I just check nothing is in the same row/col above them (since it would only be another wall or ceiling). It's the floor/ceiling tiles that are difficult.

It's easy enough to check if an item has neighbouring items, or if is supported by a wall below, but I can't seem to find an efficient way to do the checks if, for example, a ceiling tile has many neighbouring tiles that it supports:

VS those same neighbouring tiles, but they are supported by another item:

I thought maybe I should be storing the information about which other items support the current item during placement, but that just feels like moving the same complexity to another part of the code.

Is there and algorithm or concept that I could use/adapt to do the checks?

# Answer
You can run a breadth-first search from the ground, and each time you encounter a new piece, you mark it with an integer `distanceToGround` equal to the current generation of the search. (So objects directly touching the ground get marked with a 1, those touching an object directly touching the ground get marked with a 2, etc...)

Then when you want to delete an object, you check the `distanceToGround` value of the object to remove and all of its neighbours. If all the neighours have an equal or lower `distanceToGround`, you can remove the object safely - none of the neighbouring objects' paths to the ground could go through this piece or they'd have a higher number.

If you do find an object with a higher `distanceToGround`, then you'll need to verify it has an alternate path available. Do a search from that object (excluding the object you want to remove), looking for another one with a lower `distanceToGround` than the neighbour you started from.

If you find one, then this object has an alternate path to the ground through this alternate root (we'll come back to it later). If you can't find anything lower without going through the object to remove, then it can't be removed without stranding some parts.

When you do remove the object, you'll need to update the `distanceToGround` numbers for any objects downstream from the alternate roots we identified in our searches, so that the invariant holds for the next time we want to test an object removal.
> 2 votes

# Answer
First you'd need to check if the object has any neighbors. If not, it can be deleted.

If the object does have neighbors, you'll need to check each of its neighbors and see if they ALL touch the ground. If they do, the object can be deleted.

If one of the neighboring objects does not touch the ground, you'll need to check if it can be deleted using the same rules as above.

It should come out to something like this. I added the `alreadyChecked` to avoid causing an infinite loop resulting in a `StackOverFlowException` You'd call this by passing the object you want to delete for `objToDelete` and `null` for `alreadyChecked`. I'll continue editing as I keep thinking it over.

```
public bool CanDelete(GameObject g, ref List<GameObject> alreadyChecked)
{
    if (objToDelete.Neighbors.Count == 0)
        return true;

    if (alreadyChecked == null)
        alreadyChecked = new List<GameObject>();

    bool allCanBeDeleted = true;
    foreach (GameObject n in objToDelete.Neighbors)
    {
        if (alreadyChecked.Contains(n)
            continue;

        alreadyChecked.Add(n);

        if (!n.touchesGround)
            if (!CanDelete(n, alreadyChecked))
            {
                allCanBeDeleted = false;
                break;
            }
    }
    return allCanBeDeleted;
}

```
> 0 votes

---
Tags: unity, c#, mathematics, algorithm
---


title: Issues with Marching Cubes

text:
# Question
Title: Issues with Marching Cubes
so I'm trying to write a marching cubes class for my game, at the moment I have it close (I think). Right now I'm focusing on vertexes and indices. So I'm getting triangles to appear where I want them to but not how I want them to. Here's some screen shots.

And here's the source I'm using to create the mesh.

```
public class MeshGenerator {

private static int[][] vertexOffset = new int[][] { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 }, { 0, 0, 1 },
        { 1, 0, 1 }, { 1, 1, 1 }, { 0, 1, 1 } };
private static float target = 0.5f;

public static Voxel[][][] generateVoxels(int size) {
    Voxel[][][] voxels = new Voxel[size][size][size];

    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            for (int k = 0; k < size; k++) {
                voxels[i][j][k] = new Voxel(VoxelMaterial.Grass);
            }
        }
    }

    return voxels;
}

public static MeshData generateMeshMarchingCubes(Voxel[][][] voxels) {

    List<Vector3f> verts = new ArrayList<Vector3f>();
    List<Float> normals = new ArrayList<Float>();
    List<Integer> indices = new ArrayList<Integer>();
    List<Float> textureCoords = new ArrayList<Float>();

    for (int x = 0; x < voxels.length; x++) {
        for (int y = 0; y < voxels.length; y++) {
            for (int z = 0; z < voxels.length; z++) {

                if (voxels[x][y][z].getMaterial() == VoxelMaterial.Air) {
                    continue;
                }

                float[] cube = new float[8];

                if (checkIfExpose(voxels, x, y, z, cube) == false) {
                    continue;
                }

                MarchCube(new Vector3f(x, y, z), cube, verts, indices);

                normals.add(0f);
                normals.add(1f);
                normals.add(0f);

                textureCoords.add(0f);
                textureCoords.add(1f);
            }
        }
    }

    MeshData data = new MeshData();
    data.setIndices(UniversalFunctions.intListToArray(indices));
    data.setVertsFromVector3f(verts);
    data.setNormals(UniversalFunctions.floatListToArray(normals));
    data.setTextureCoords(UniversalFunctions.floatListToArray(textureCoords));

    return data;
}

private static boolean checkIfExpose(Voxel[][][] voxels, int x, int y, int z, float[] cube) {

    Voxel[] surroundingVoxels = getSurroundingVoxels(voxels, x, y, z);
    boolean bool = false;

    for (int i = 0; i < surroundingVoxels.length; i++) {
        if (surroundingVoxels[i].getMaterial() == VoxelMaterial.Air) {
            cube[i] = 0;
            bool = true;
        } else {
            cube[i] = 1;
        }
    }

    return bool;
}

private static Voxel[] getSurroundingVoxels(Voxel[][][] voxels, int x, int y, int z) {

    int maxLength = voxels.length;
    List<Voxel> voxelList = new ArrayList<Voxel>();

    if(y - 1 > 0 && y - 1 < maxLength) {
        voxelList.add(voxels[x][y - 1][z]);
    } else {
        voxelList.add(new Voxel(VoxelMaterial.Air));
    }

    if(x - 1 > 0 && x - 1 < maxLength) {
        voxelList.add(voxels[x - 1][y][z]);
    } else {
        voxelList.add(new Voxel(VoxelMaterial.Air));
    }

    if(z - 1 > 0 && z - 1 < maxLength) {
        voxelList.add(voxels[x][y][z - 1]);
    } else {
        voxelList.add(new Voxel(VoxelMaterial.Air));
    }

    if(z + 1 > 0 && z + 1 < maxLength) {
        voxelList.add(voxels[x][y][z + 1]);
    } else {
        voxelList.add(new Voxel(VoxelMaterial.Air));
    }

    if(x + 1 > 0 && x + 1 < maxLength) {
        voxelList.add(voxels[x + 1][y][z]);
    } else {
        voxelList.add(new Voxel(VoxelMaterial.Air));
    }

    if(y + 1 > 0 && y + 1 < maxLength) {
        voxelList.add(voxels[x][y + 1][z]);
    } else {
        voxelList.add(new Voxel(VoxelMaterial.Air));
    }

    return voxelList.toArray(new Voxel[voxelList.size()]);
}

// MarchCube performs the Marching Cubes algorithm on a single cube
private static void MarchCube(Vector3f pos, float[] cube, List<Vector3f> vertList, List<Integer> indexList) {
    int i, j, vert, idx;
    int flagIndex = 0;
    float offset = 0.0f;

    Vector3f[] edgeVertex = new Vector3f[12];

    for(int inter = 0; inter < 12; inter++) {
        edgeVertex[inter]  =  new Vector3f();
    }

    // Find which vertices are inside of the surface and which are outside
    for (i = 0; i < 8; i++) {
        if (cube[i] <= target) {
            flagIndex |= 1 << i;
        }
    }

    // Find which edges are intersected by the surface
    int edgeFlags = MarchingCubesCases.cubeEdgeFlags[flagIndex];

    // If the cube is entirely inside or outside of the surface, then there will be
    // no intersections
    if (edgeFlags == 0)
        return;

    // Find the point of intersection of the surface with each edge
    for (i = 0; i < 12; i++) {

        // if there is an intersection on this edge
        if ((edgeFlags & (1 << i)) != 0) {
            offset = GetOffset(cube[MarchingCubesCases.edgeConnection[i][0]],
                    cube[MarchingCubesCases.edgeConnection[i][1]]);

            edgeVertex[i].x = pos.x + (vertexOffset[MarchingCubesCases.edgeConnection[i][0]][0]
                    + offset * MarchingCubesCases.edgeDirection[i][0]);
            edgeVertex[i].y = pos.y + (vertexOffset[MarchingCubesCases.edgeConnection[i][0]][1]
                    + offset * MarchingCubesCases.edgeDirection[i][1]);
            edgeVertex[i].z = pos.z + (vertexOffset[MarchingCubesCases.edgeConnection[i][0]][2]
                    + offset * MarchingCubesCases.edgeDirection[i][2]);

        }
    }

    // Save the triangles that were found. There can be up to five per cube
    for (i = 0; i < 5; i++) {

        if (MarchingCubesCases.triangleConnectionTable[flagIndex][3 * i] < 0) {
            break;
        }

        idx = vertList.size();

        for (j = 0; j < 3; j++) {
            vert = MarchingCubesCases.triangleConnectionTable[flagIndex][3 * i + j];
            indexList.add(idx + MarchingCubesCases.windingOrder[j]);
            vertList.add(edgeVertex[vert]);
        }

    }
}

// GetOffset finds the approximate point of intersection of the surface
// between two points with the values v1 and v2
private static float GetOffset(float v1, float v2) {
    float delta = v2 - v1;
    return (delta == 0.0f) ? 0.5f : (target - v1) / delta;
}

```

I've checked the other look up tables multiple times and they seem good, so tbh I'm lost, I'm not sure where I'm going wrong so any help would be amazing.

Edit : I'm using the generateVoxels to create the voxels in the generateMeshMarchingCubes. The MeshData class is just a holder for the indices, certs, normals, etc for the mesh.

# Answer
So to be honest I never really solved this problem.... In java, I translated it to c# and it was working fine, so I have no idea what went wrong, I think my java let me down, but after translating it to c# and using the unity engine it was working fine
> 0 votes

---
Tags: java, lwjgl, 3d-meshes, marching-cubes
---


# Question
Title: Serialization/Deserialization Solutions for Loading & Playing Audio Files
I'm creating a music game in unity, and the first issue I encountered was that I had no way to load music into the game from a file. I tried using a WWW to load the mp3 files, but in my research I came across multiple sources that told me that this method would not work, and I was unable to get it to work in my own practice.

So, I found the Naudio library, which allowed me to convert the MP3 files to an array of floats which I then used `AudioClip.SetData()` to create an audio clip with. To avoid having to do this conversion every time I wished to load a new song, I thought to then serialize the converted audio data to a binary file which I would then deserialize to create a new audio clip when the song is requested, and that audio clip is then stored in a list for if I need it later during runtime.

This worked for a long time, but now I'm almost ready to ship my game and I'm realizing that the file sizes for these binary files are massive - upwards of 100MB in most cases of a 4 minute song. This is obviously unacceptable considering that the file size of a regular MP3 song of that length is less than a tenth of that.

So, I looked into using a DeflateStream when serializing and my research brought me to the DotNetZip library, which someone recompiled for use with Unity here. However, this did little to remedy my issue because 1) The compressed file sizes were smaller, but not small enough (still around 50MB for a 4-minute song), and 2) The time it takes to serialize the file skyrocketed from 3-5 seconds to upwards of 30 seconds.

Perhaps I'm looking at this problem the wrong way. Can anyone offer me some insight as to how I can load and play mp3 files at runtime?

# Answer
Unity internally uses ogg vorbis for audio - whenever you drop an mp3 into your Unity project, the editor converts it to vorbis and uses that. Importantly, this means Unity can natively decode ogg vorbis audio files at runtime including streaming them via WWW.

So, rather than essentially creating a new binary audio format (both ogg and mp3 do some very complex audio processing to achieve the level of compression they reach), use the ogg decoder to your advantage. Convert your mp3's to ogg and stream those in via WWW instead.

If however you need to stream mp3, you could include NAudio in your project and run the mp3 decode at runtime but instead of decoding the entire file, use a streaming AudioClip instead. Unity AudioClips have a 'stream' mode which raises an event called PCMReaderCallback \- this event just asks for the next chunk of floats right when it needs them. Hook in the mp3 decoder *here* for minimal memory use and almost no startup delays as it'll be decoding on demand instead.
> 3 votes

---
Tags: unity, c#, audio, serialization, compression
---


# Question
Title: How can I scale object on one side only with a speed factor?
```
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ScaleOneSide : MonoBehaviour
{
    public float speed = 1;

    float mfX;
    float mfY;
    // Use this for initialization
    void Start()
    {
        mfX = transform.position.x - transform.localScale.x / 2.0f;
        mfY = transform.position.y - transform.localScale.y / 2.0f;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Vector3 v3Scale = transform.localScale;
            //transform.localScale = new Vector3(v3Scale.x + 0.1f, v3Scale.y + 0.1f, v3Scale.z);
            //transform.position = new Vector3(mfX + transform.localScale.x / 2.0f, mfY + transform.localScale.y / 2.0f, 0);

            //transform.localScale = new Vector3(v3Scale.x + 0.1f, v3Scale.y, v3Scale.z);
            transform.position = new Vector3(mfX + transform.localScale.x / 2.0f, 0, 0);

            transform.localScale = Vector3.Lerp(transform.localScale, new Vector3(v3Scale.x + 0.1f,0,0), speed * Time.deltaTime);
        }
    }
}

```

When using only this two lines it was working fine without changing the speed:

```
 //transform.localScale = new Vector3(v3Scale.x + 0.1f, v3Scale.y + 0.1f, v3Scale.z);
   //transform.position = new Vector3(mfX + transform.localScale.x / 2.0f, mfY + transform.localScale.y / 2.0f, 0);

```

But now I'm trying to add to the scaling a speed. I want when I press the mouse left button it will scale the object according to the speed.

# Answer
> 1 votes
If you are familiarized with **Coroutines** you could try handing the scaling there.

Why? well since using **Lerp** with the parameter time t as a speed that may be constant and a **deltaTime** that just references the change of time between frames will give you most of the times values in one range, so you may see come jiggering there. That is because **Lerp**, as any interpolation function, receives a normalized property t that goes between 0.0 and 1.0, where 0.0 is your initial value, and 1.0 is the desired value.

You have already the data you need, you just need to put it in a coroutine, like this:

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

public class ScaleOneSide : MonoBehaviour
{
    public float speed = 1f;

    float mfX;
    float mfY;
    // Use this for initialization
    void Start()
    {
        mfX = transform.position.x - transform.localScale.x / 2.0f;
        mfY = transform.position.y - transform.localScale.y / 2.0f;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            StartCoroutine(Scale(new Vector3(v3Scale.x + 0.1f, 0f, 0f)));
        }
    }

    IEnumerator Scale(Vector3 _newScale)
    {
        float n = 0.0f;
        Vector3 originalScale = transform.localScale; // It is important to have your scale reference before interpolating.

        while(n < 1.0f)
        {
            transform.localScale = Vector3.Lerp(originalScale, _newScale, n);
            n += Time.deltaTime / speed; // here your normalized t will increment from 0 to 1.
            yield return null;
        }

        transform.localScale = Vector3.Lerp(originalScale, _newScale, 1.0f); // Just to make sure it scales to the destiny point, since n doesn't always reach 1.
    }
}

```

You can also do this with update, but it gives you less code handling, in my personal experience, since it is best to separate functionality when possible.

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


# Question
Title: Is it possible to make an obj with single triangle
I am not good in using blender so i wanted to ask if it is possible to make an object with just one triangle and how would it look like, will the no of triangle increase if you scale it up.

# Answer
A mesh with just a single triangle is perfectly possible.

It would look like a triangle. Nothing particularly surprising.

Scaling it up won't automatically add more triangles, unless you use something like a tessellation shader to dynamically subdivide it.

It sounds like you might be trying to do something more involved though — if you edit your question to describe the problem you're trying to solve or the ultimate effect you want to use this to achieve, we might be able to give you a more constructive answer.
> 1 votes

---
Tags: unity, blender
---


# Question
Title: DX11 swap chain is 1 frame behind when presenting to screen and using multisampling
After adding multisampling to a DirectX 11 project, I noticed that the screen was no longer updating when calling `IDXGISwapChain ::Present`. Further testing showed that it was in fact updating the screen, but it was always 1 frame behind. If I added a line to the scene and presented it, I wouldn’t see that line until I do the next present call. This behavior is specific to the use of multisampling. If I turn multisampling off, the behavior goes away. This behavior is also specific to my Intel display adapter. If I use my Nvida display adapter, the behavior goes away.

The multisampling settings are determined by using `ID3D11Device::CheckMultisampleQualityLevels`, and the creation of the back buffer and depth stencil work, so I don’t think the settings themselves are incorrect in any way. Also the multisampling does work; the end result is properly multisampled. I have played with various multisampling settings within the available range, and all settings produce the same behavior. Just in case I’m doing something wrong, I tried using the debug layer, but got no warnings or errors.

Through hours of testing, I found two work-arounds:

**1 - Call Present twice:**

```
HRESULT result = _swapChain->UnmanagedPointer->Present(0, 0);
if (result != S_OK)
    ExceptionThrower::Throw(result, "Failed to present the swap chain buffer.");

result = _swapChain->UnmanagedPointer->Present(0, 0);
if (result != S_OK)
    ExceptionThrower::Throw(result, "Failed to present the swap chain buffer.");

```

When I do this, the second `Present` call puts the correct information on screen.

**2 - Call `ID3D11DeviceContext::Flush` after Present**

```
HRESULT result = _swapChain->UnmanagedPointer->Present(0, 0);
if (result != S_OK)
    ExceptionThrower::Throw(result, "Failed to present the swap chain buffer.");

_d3dDeviceContext->Flush();

```

After the `Flush` call, the correct information is on screen.

As I understand it, both of these work arounds incur a significant penalty, so I would rather find a better solution (if on exists). I especially dislike this work around because it penalizes everyone. There is no way for me to know when this behavior is happening. I have a feeling that I may be dealing with a driver bug since this is only an issue with the Intel adapter. I hate to force all scenarios to add this overhead when for most, it won’t be necessary. Oh and in case someone asks, I have updated the Intel drivers to the most recent, but it’s an old adapter, so these drivers date back to 2012.

Has anyone seen this type of behavior before? Is there a better work around, or perhaps a solution I’m not aware of? If forced to use one of the two work arounds, which of the two would be the best? I’m leaning towards the second (Flush call), but not sure.

In case helpful, here is my swap chain creation code

```
DXGI_SWAP_CHAIN_DESC desc;
ZeroMemory(desc, sizeof(DXGI_SWAP_CHAIN_DESC));

desc.BufferDesc.Width = width;
desc.BufferDesc.Height = height;
desc.BufferDesc.RefreshRate.Numerator = 60;
desc.BufferDesc.RefreshRate.Denominator = 1;
desc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
desc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;

desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
desc.BufferCount = 1;
desc.SampleDesc.Count = 1;
desc.SampleDesc.Quality = 0;
desc.OutputWindow = outputWindow;
desc.Windowed = true;
desc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
desc.Flags = 0;

if (useMultiSampling)
{
    desc.SampleDesc.Count = _multiSampleCount;
    desc.SampleDesc.Quality =  _multiSampleQuality - 1;
}

```

# Answer
> 2 votes
To present an MSAA back-buffer, it must be resolved (i.e. the multiple samples per pixel need to be reduced to a single pixel) before it can be composited and shown to the user. For older presentation modes with DXGI (`DXGI_SWAP_EFFECT_DISCARD` or `DXGI_SWAP_EFFECT_SEQUENTIAL`) and with Direct3D 9, this is 'magic' done behind the scenes on your behalf which likely introduces the additional frame of latency.

For both the Universal Windows Platform (UWP) apps and Direct3D 12 generally, this old model is not supported: i.e. trying to create a backbuffer with a `SampleDesc.Count` \> 1 will result in a failed call--basically when you use `DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL` or `DXGI_SWAP_EFFECT_FLIP_DISCARD`.

You instead implement MSAA resolves directly. You create your render target as MSAA and then explicitly call `ResolveSubresource` to get it from your MSAA render target to the backbuffer for presentation.

> Note that one additional complication here is if your render target is an `SRGB` format. Resolve won't handle the gamma-correction, so you typically have to use `ResolveSubresource` from your SRGB MSAA Render Target to an SRGB Render Target, then render as a full-screen quad the SRGB Render Target onto the final backbuffer which is not SRGB.

# Answer
> 1 votes
Additionally, you haven’t specified the refresh rate correctly. As a result, transitions to full screen mode would result in DXGI using blit as opposed to flip. The correct value is 60000 for the numerator and 1001 for the denominator. Even better, enumerate the display modes from the adapter and use the values contained therein.

---
Tags: directx11, multisampling
---


# Question
Title: Does anything need to be done to support variable refresh rate?
Does anything have to be done in order for my game to take advantage of variable refresh rate technology supported by some displays, such as G-SYNC and FreeSync?

# Answer
Roughly speaking, no, nothing special.

For some drivers/systems you must run in exclusive fullscreen mode, but otherwise these technologies are transparent to the application.

Note that you need to actually be able to take advantage of faster refresh rates to see any benefit. Your game's logic will run at a fixed timestep (fix your timestep so you need to be able to animate and render on an independent an unfixed timestep.

Note that some games might appear to have jerky animations with adaptive sync (or just a high frame rate monitor) that otherwise appear smooth on non-adaptive systems with vsync enabled. That behavior can be caused by games with wildly varying frame times (which *can* be a problem with vsync if the frame times oscillate widely enough to bounce the game between 30hz and 60hz). The reason is because animations are generally advanced by the prior frame's time, so oscillating frame times mean you might have (for exmample) a 5ms frame followed by a 10ms frame that only advanced animations by 5ms followed by a 7ms render that advanced animations by 10ms, and so on. You want frame times to smoothly change over time and not jump around a lot. That can be a lot more easily said than done for some games, though.
> 2 votes

# Answer
It depends which API you’re using to develop your game. Direct3D has a SwapChain flag AllowTearing, in addition to a Present() parameter of the same name. These are specifically for supporting variable refresh displays, where your Vertical Sync option (in the case of nVidia) is set to “Fast”.
> 1 votes

---
Tags: opengl, c++, frame-rate
---


# Question
Title: Unity2D: Wrapping a line around an object
I have this 2d platformer made out of box colliders. I have the player connected to a point by a LineRenderer and a DistanceJoint2D, for use in physics puzzles. This tool lets him link to a location and then do grappling hook things with it, like retract the rope at speed to spiderman around.

What I want to do is move the distance joint around the object, thus changing the angle at which the player is pulled. Like in this image.

Very similar to this more general, unanswered question that doesn't not give any specific math.

I know I'll be making a list of positions and then move the joint's anchor around whenever it wraps/unwraps, but I'm not sure how to tell when and where it wraps on something.

# Answer
> 1 votes
Right, so.

How I ended up doing this was by switching all my platform/wrapping around objects from BoxCollider2Ds to PolygonCollider2Ds. Boxes can't be asked for their corners as they are defined as a center point with height and width, but poly colliders will return a list of Vector2 if you use `polycollider.points`.

Then, in `Update` I just sent a raycast from my character to the last point, and asked the object hit for the .points, and compared them to the raycast collision coordinates, and added the closest fit to the list of points.

and to unwrap you calculate the angle of the last three points in the linerender, if it is bigger than 180, snip that last point from the list!

TL;DR

* Only use polycollider2D for your platforms
* On update send raycast along rope
* On collision use .points to get list of corners
* compare corners to raycast collision point
* add closest corner to list/linerender/joint/whatever else you need

I was greatly aided by the tutorial found here: www.raywenderlich.com/171250/make-2d-grappling-hook-game-unity-part-1

# Answer
> 0 votes
When the `BoxCollider2D` that is the rope, collides with the `BoxCollider2D` that is the platform, a collision callback will occur, whose argument will be a `Collision2D` containing the pertinent contact data. You'll know *which* platform collided with the rope from the `Collision2D`, and then check that body's 4 corners against the collision point using `Vector2.magnitude`, to see which is the nearest corner. That's where you'll create the joint. If it is created too close, don't worry, as any inter-penetration will be resolved automatically by the physics engine pushing the rope and its associated (new) joint(s) away from the platform box itself.

You also need to know, as the rope swings back down again, the point in time at which you should remove extraneous joints. This will happen the moment the angle of any sub-joint rope sections angles reach or exceed ("cross over") the angle they had at the moment when they split off. You could just check the subsection's angle against its parent rope section's angle to know for sure.

---
Tags: unity, 2d, collision-detection, platformer, joints
---


# Question
Title: How does the render performance of Magicavoxel objects compare to standard Cube objects?
What would be easier to render by the computer:- 1) an obj made in magicavoxel of 50\*100\*1. 2)an cube in unity with same dimensions with any material or an png image.

# Answer
A Cube will have less tris and will be rendered in one draw call
> 1 votes

---
Tags: unity
---


# Question
Title: How to make a 90 degree rotation happen over time
I'm trying to take a RotateAround function and make it happen over time. I've been tinkering with Quaternions to try and get it to work but I can't quite figure it out.

This is the code:

```
public class RotateCamera : MonoBehaviour {

public Vector3 rotatePoint = new Vector3(0,0,5);

public void RotateLeft ()
{
    transform.RotateAround (rotatePoint, Vector3.up, 90);
}

public void RotateRight ()
{
    transform.RotateAround (rotatePoint, Vector3.up, -90);
}

```

I'm applying each void to a button, and this works like a Final Fantasy Tactics camera - rotate an isometric camera 90 degrees. But it happens instantly, and I want to make it happen over time, like a second or a half a second. I'm super new to programming and I can't find any guides on this or any other posts using google, so I'm asking on here as a last resort. Thanks for any help.

# Answer
There would be numerous ways to implement this effect, because there are many ways to do timed transitions and rotations.

The general steps to take could be something like this

* Store `start_time = now`
* Store `start_rotation = x`
* Calculate `end_time = now + 60`
* Calculate `end_rotation = y`

Now at any time you can calculate a linear parameter `p = (time - start_time) / (start_time - end_time)`. If `time` is between `start_time` and `end_time` then `p` will be between 0 and 1.

This allows us now to do linear interpolation of any value, for example the rotation value. You can choose to do linear interpolation on the Euler angle,

```
start_rotation = 90
end_rotation = -90
r = start_rotation + p * (end_rotation - start_rotation)
transform = initial_transform
current_rotation = transform.Rotate(0, -45, r)

```

uusing `RotateAround` from a default position,

```
start_rotation = 90
end_rotation = -90
r = start_rotation + p * (end_rotation - start_rotation)
transform = initial_transform
current_rotation = transform.RotateAround(rotatePoint, Vector3.up, r)

```

or using quaternions

```
current_rotation = Quaternion.Slerp(start_rotation, end_rotation, p)

```
> 1 votes

# Answer
When you want to kick off an action that will play out over several frames, a Coroutine is often a convenient way to do this. Here's one way to use a Coroutine for this purpose:

```
public Vector3 rotatePoint = new Vector3(0,0,5);
public float rotationSpeed = 90f;

Quaternion _targetRotation;
Vector3 _localOffset;
Coroutine _rotationCoroutine;

public void Start() {
    // Remember where the center of rotation should be in our local space.
    _localOffset = transform.InverseTransformPoint(rotatePoint);
    _targetRotation = transform.rotation;
}

public void RotateLeft () { Rotate(90); }

public void RotateRight () { Rotate(-90); }

void Rotate(float increment) {
    // Spin our target rotation in the desired direction.
    _targetRotation = Quaternion.Euler(0, increment, 0) * _targetRotation;

    // If we're not already rotating, start a new rotation.
    // (Otherwise, the coroutine will automatically handle the new target)
    if(_rotationCoroutine == null)
        _rotationCoroutine = StartCoroutine(RotationCoroutine());
}

IEnumerator RotationCoroutine() {
    // Until our current rotation aligns with the target...
    while(Quaternion.Dot(transform.rotation, _targetRotation) < 1f) {
        // Rotate at a consistent speed toward the target.
        transform.rotation = Quaternion.RotateTowards(
            transform.rotation,
            _targetRotation,
            rotationSpeed * Time.deltaTime
        );

        // Adjust our position to preserve the relationship to the pivot.
        Vector3 offset = transform.TransformPoint(_localOffset);
        transform.position = rotatePoint - offset;

        // Wait a frame, then resume.
        yield return null;
    }

    // Clear the coroutine so the next input starts a fresh one.
    _rotationCoroutine = null;
}

```
> 1 votes

# Answer
In the inspector rotate your camera to the desired position and enter those values in the script area. Click left and right arrows on your keyboard, and adjust the time.

```
public class RorateCamera : MonoBehaviour
{
    public Vector3 rightRotation;
    public Vector3 leftRotation;
    public float speed = 0.1F;

    private bool rotateRight;

    public void RotateLeft()
    {
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(leftRotation), Time.deltaTime * speed);
    }

    public void RotateRight()
    {
        transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(rightRotation), Time.deltaTime * speed);
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.LeftArrow))
        {
            rotateRight = false;
        }
        if (Input.GetKeyDown(KeyCode.RightArrow))
        {
            rotateRight = true;
        }

        if (rotateRight)
        {
            RotateRight();
        }
        else
        {
            RotateLeft();
        }
    }
}

```
> 0 votes

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


# Question
Title: Singleton pattern Class attached to multiple GameObjects still only 1 instance?
I'm currently working on an Inventory/Equipment System and so far have been using a Singleton Pattern to instantiate my Inventory and Equipment classes. I was wondering if i attach this Script to multiple gameObjects, whether they each have a seperate instance or whether they share it? This would be important for the Equipment classes as each GameObject should obviously have different Items equipped. My current Singleton pattern looks like this:

```
public static Inventory Instance { get { return instance; } }

void Awake()
{
    if(instance != null && instance != this)
    {
        Destroy(this.gameObject);
        Debug.LogWarning("More than one instance of Inventory found!");
        return;
    }
    instance = this;
}

```

# Answer
> 0 votes
If you need different instances of the inventory for different game objects, but want to ensure that you always have one single inventory per game object, then the singleton pattern is not the right pattern here.

I would simply use a read-only field or property for the inventory

```
public class MyGameObject : GameObject
{
    public Inventory Inventory { get; } = new Inventory();
}

```

Like this, each game object having an inventory creates his own single inventory being distinct from inventories of other game objects.

Note: Read only means that you cannot delete or replace the inventory object; however, you can still add objects to or remove objects from the inventory.

---

Probably some kinds of objects have an inventory, others do not. E.g. a treasure box has an inventory, while a stone doesn't. Therefore I would create an interface for the better distinction

```
public IInventoryHolder
{
    Inventory Inventory { get; }
}

public class MyGameObject : GameObject, IInventoryHolder
{
    public Inventory Inventory { get; } = new Inventory();
}

```

Then instead of having statements like

```
if (gameObject is TreasureBox || gameObject is Player || gameObject  is whatever...) {
    gameObject.Inventory.Add(item);
}

```

You can write

```
if (gameObject is IInventoryHolder inventoryHolder) {
    inventoryHolder.Add(item);
}

```

# Answer
> 1 votes
> I was wondering if i attach this Script to multiple gameObjects, whether they each have a seperate instance or whether they share it?

Well, let's walk through the code to see what happens.

Let's say we have this script attached to **Object1** and **Object2**, and Object1 happens to load first....

**Object1**

```
// Object1's inventory script's Awake() gets called.
void Awake()
{
    // Nothing has yet set instance, so instance == null.
    if(instance != null && instance != this)
    {
        // The if test fails, and we skip over the part inside the braces.
    }
    // instance is now set to point to Object1's inventory script
    instance = this;
}

```

So, at the end of Awake, `instance` is pointing to Object1's attached inventory script.

Now Object2 loads...

**Object2**

```
// Object2's inventory script's Awake() gets called
void Awake()
{
    // Now instance is not null, it's pointing at Object1's inventory script.
    // But "this" is Object2's inventory script, so instance != this.
    if(instance != null && instance != this)
    {
        // We enter the if, Destroy Object2, log a warning, and exit early.
        Destroy(this.gameObject);
        Debug.LogWarning("More than one instance of Inventory found!");
        return;
    }
    // Since we exited early, nothing else happens.
}

```

So, the result is that you have only one instance of the inventory script in existence, because all the other objects that had the inventory script attached destroy themselves on load.

If this is not your desired behaviour, then this might not be the right pattern for your application. Unfortunately, we don't have enough context about what you're trying to do to know for sure what you might need instead. Feel free to ask a new question describing your application & how the feature should work if you need some tips on how to achieve it.

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


# Question
Title: Most Efficient Way To Get Objects In A Rectagular Area - Unity2D
*First of all, if you know a better way to do what I want to achieve please don't hesitate to suggest your own method.*

What I want to do is the classic area selection in RTS games, which player drags his mouse to draw a rectangle and units inside rectangle become selected.

At this point, I have two ideas:

1. A dedicated gameObject with a trigger BoxCollider2D.
2. Detecting overlaps with Physics2D.OverlapArea method.

In the first method, the gameObject will get resized on the fly while the user drags and by using collision control the objects get selected.

In the second method starting point and end point of the area is being recorded and script draws an OverlapArea using these two coordinates.

Which one would be more effective in terms of performance?

Thanks in advance.

# Answer
I would definitely go with the second method. In this manner, you don't have to have anything firing in your physics engine, or have to deal with disabling/enabling colliders when you are not using them.

The second method also has the added benefit of having Point1 and Point2 parameters, which coincide with your drag/draw selection interface. You are going to start dragging at Point1 and release at Point2.

Using the second method for this mechanic is the way to go.
> 4 votes

# Answer
I would definitely look at this link: RTS style Unit selection

It is very well done. You will need to do a little bit of optimalization yourself tho.

I use it in my RTS game and it works much better than the other solutions i tried.
> 0 votes

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


# Question
Title: How can I render 3d pictures synched frame by frame to a keyed video?
I'm developing a software that aims to combine a keyed video with a 3D rendered one, synchronously frame by frame.

Each frame of video should be combined with a timely corresponding frame of 3D picture using a matching camera position parameter.

How can I perform this rendering and ensure it stays in synch?

# Answer
> 1 votes
One thing you'll need to contend with is making sure both the 2D video and the 3D scene produce a frame in a timely manner. Typically video is kept in compressed form on disk/network and is read a little at a time to decompress each frame and then display it. Likewise, 3D scenes may have what's currently visible in memory, and then load more geometry/textures/etc. from disk/network/etc. when needed. This could cause I/O contention if both geometry and video need to be loaded at the same time. If you can keep much of it in memory, you'll reduce I/O contention between the 2 tasks.

Additionally, video will need to be decompressed usually and that takes up CPU time. If you know your target machine, you may be able to optimize your threading strategy to have 1 (or a few) thread(s) doing video decompression while another thread (or threads) deals with your 3D needs. Furthermore, different codecs have different amounts of CPU requirements. You can experiment with different compression schemes to see which gives you a good trade-off of compressed size vs. decompression cost. Usually more highly compressed video will reduce IO overhead as fewer bytes need to be read from disk or network, but high quality, highly compressed video may be more expensive to decompress.

The best thing to do is come up with an implementation and profile it. Without having any specifics on type of video, complexity of 3D scene, etc., nobody can even begin to guess where your bottlenecks will be. Running real-world tests and measuring is your best bet for figuring this out.

---
Tags: rendering, frame-rate
---


title: Procedural Star Generator

text:
# Question
Title: Procedural Star Generator
I want to develop a procedural galaxy / starfield generator.

A rather simple approach would be to use some pseudo-random algorithm to repeatedly create a star and its properties (such as position, mass, luminosity, density, and so on...). But in doing that, I would be quite limited in terms of the total number of stars. They would all be created at startup, and kept in memory, even the ones which are totally out of the player's range.

I do not want to end up with millions of star instances.

What I need is some way to only generate the stars which are near to the player and, therefore, being rendered. On the other side, I want the player to be able to return to stars, once they disappear due to being too far away. Take Space Engine for example, it also does not generate all its trillion stars at the start of the simulation.

What would be a suitable approach to this kind of problem?

# Answer
> 5 votes
Divide your universe into cubic chunks. You only generate the chunks around the player. When the player moves, release the memory occupied by the chunks further away from the player.

Generate the stars and other objects in each chunk with a pseudorandom number generator which you seed with the coordinates of the chunk. Using the same seed will result in the same sequence of random numbers. That means you can re-generate each chunk again and again and it will always turn out exactly the same.

If you want to render and calculate further away chunks with a lower level of detail (like only the stars for far away chunks, planets for closer chunks, asteroids and ships for the chunk the player is in or adjacent to), have your chunk generation algorithm generate the low-detail things first and the high-detail things later. That way you can execute the generation algorithm only to a certain level of detail and continue running it for more details when the player comes closer.

All you need to keep stored are any changes the player's activities caused to a chunk. When this becomes too much data to handle, consider saving the state of unloaded chunks to the hard drive. When you unload a chunk, save its state to a file. Read and re-apply the change-file for the chunk when the player returns.

---
Tags: mathematics, algorithm, procedural-generation, random
---


title: Breakout paddle bouncing

text:
# Question
Title: Breakout paddle bouncing
I am having trouble with making a Breakout Clone using JavaFX. I have almost everything working, but I have a problem with the physics of the ball after it bounces off of the paddle. I used this question to get the physics working with the paddle, but only slightly. Instead of working nice and clean after switching around x and y values, the ball will sometimes end up getting stuck inside the paddle and jittering back and forth very rapidly instead of bouncing off. I have tried getting a "future version" of the ball, by checking where it would be on the next frame, but it still ends up doing the same thing. My code is here for anyone who is interested (it is all one class file, so I figured I would just use a pastebin).

Thanks in advance for any help!

**EDIT:** If anyone needs a video of what is happening, I will post one.

# Answer
> 1 votes
The ball bounces "off" the paddle but because it's still inside the paddle it bounces again back into, and again, and again.

This is what causes the jittering.

The solution is to check the direction and only bounce the ball when it's moving toward the paddle.

There's a few other solutions which may at times be adequate:

* Rewind the ball back to before contact so it's not inside the paddle after a bounce. Caveat: This still causes issues when the ball can hit the sides of the paddle and the paddle can move under player control into the ball.
* Force the ball out of the paddle height. Caveat: causes an instant motion that doesn't look quite right.
* Disable bouncing the ball off the paddle for a short time after hitting the paddle. Caveat: May not be possible if your game feature enemies or bricks that can get very close to the paddle.

# Answer
> 1 votes
In your code you have

```
if (dot.getCenterY() <= brick.getY() || dot.getCenterY() >= brick.getY()+brick.getHeight())
                        dotVelY *= -1;

```

This makes it so that the ball changes it's Y velocity anytime it hits the paddle. We don't want that.

To fix your issue just make it so that the ball's velocity is reversed ONLY when the velocity.y is greater than zero (the ball is moving downwards)

The code should look something like this:

```
if ((dot.getCenterY() <= brick.getY() || dot.getCenterY() >= brick.getY()+brick.getHeight()) && dotVelY > 0)
                        dotVelY *= -1;

```

---
Tags: javafx
---


# Question
Title: What PPU should I choose for assets aimed for different resolution
So I'm trying to make my pixel-art game handle multiple resolutions. I've stumbled upon this article: https://blogs.unity3d.com/2015/06/19/pixel-perfect-2d/ but I don't understand it completely.

Let's base my question on the example from this article.

My base resolution is 1024x768, PPU is 32 and camera ortographic size is 12. How can I calculate the PPU for assets which will handle 1080p resolution?

In the article, the author took a value of 48. But simply I can't understand where did this value come from.

I'd really appreciate if someone would explain this to me.

# Answer
> 5 votes
At an orthographic size of 12, your camera sees 24 units of the world vertically.

At 32 PPU, each of those units corresponds to 32 sprite texels.

So, putting that together, your screen has \\$24 \times 32 = 768\\$ sprite texels from top to bottom, the same as the number of rows of pixels on a 1024x768 resolution, helping ensure you get crisp 1:1 rendering.

---

Now we want to get an analogous look at 1920x1080.

There's a little quirk here, in that they're no longer the same ratio. 1920x1080 is a 16:9 resolution, while 1024x768 is a 4:3 resolution, so you won't achieve an identical layout on both (not without a lot of pillarboxing). So we need to make a judgement call about how much extra world we want to show at the sides, versus how much we want to zoom in vertically.

Let's assume we still want to see exactly 24 units of the world vertically (ie. we don't want to change our camera at all, and we'll just accept that players on wider screens see more to the left & right).

\\$1080 \div 24= 45\\$, so if we make each unit of the world 45 sprite texels (ie. PPU = 45), then we'll still get an exact 1:1 alignment with the screen's pixel grid.

That's not the same number as the article chose though. So what happens if we pick 48 instead like the article did? \\$1080 \div 48 = 22.5\\$ so we can't quite fit 24 of these sprite units vertically on the screen anymore. We'd need to zoom in our camera slightly, to an orthographic size of \\$22.5 \div 2 = 11.25\\$. We can still see 93.75% as much of the height as we could at 1024x768, so the author probably felt this was a pretty good compromise, and let them keep their sprite size a multiple of a power of two (\\$48 = 3\times16\\$).

With 32-pixel sprites, we can also hit 720p and 1440p (with pixel doubling) at this same 11.25 orthographic size, so it helps us keep a consistent camera framing across a range of popular screen resolutions.

We could pick any PPU we wanted and come up with a corresponding orthographic camera size to keep it in pixel perfect alignment with the screen grid. eg. If we use a PPU of 50, then \\$1080 \div 50 = 21.6\\$ so we can make this work with an orthographic size of \\$21.6 \div 2 = 10.8\\$

---

So you can see there's not just one true PPU to use for a given set of resolutions - it depends what you want to prioritize, and what numbers look nice for the way you're handling your sprites (eg. maybe you always want even numbers so you can do tiling checkerboard patterns)

Whatever number you choose, you just want to ensure that:

$$k \times \left(\text{orthographic size} \times 2\right) \times \text{PPU} = \text{vertical screen resolution}$$

for some integer \\$k = 1, 2...\\$ - this will ensure you get an integer ratio of pixels per sprite texel so your pixel art stays sharp.

---
Tags: unity, pixel-art
---


# Question
Title: OpenGL: How to render a "shadow" for an object that's behind another?
First off, an image from Fez that depicts the effect I'm after:

I'm trying to achieve a similar effect in my project. I'm quite certain this is done with a stencil buffer, but the resources on such effect are scarce. How should I approach this? I'm guessing I'm after a sort of "AND" stencil where I'd render a semi-transparent black rectangle over the player where only the pixels that had both the player and a map object.

I'm not sure if it has any effect on it (besides maybe inverting the stencil operations..?), but for other reasons, my pipeline first renders the world and the player is rendered last.

# Answer
> 1 votes
One simple way to do this for a sprite game like this is:

1. Render your world
2. Render your player shadow

* disable depth testing & writing so the shadow draws over closer objects, but doesn't modify the depth stored there
    * use the player sprite's alpha to control the silhouette, but render just a semi-translucent black instead of the sprite's colour
3. Render your player sprite

* depth testing & writing re-enabled
    * normal sprite rendering

Since your player sprite is drawn after the shadow, it will completely hide it anywhere the player is visible, and leave the shadow visible anywhere the player is occluded.

You have to get a little fancier when doing this in 3D because meshes can have self-intersections, but for sprites you can get a bit sloppy and it still works - especially if your world is hard-edged & alpha tested like in this example.It gets a bit more complicated though if you need correct depth sorting for alpha blended sprites, if they're allowed to show the shadow too.

---
Tags: opengl, graphics-programming, stencil
---


# Question
Title: Turning a simple HTML5/JS single-player game into a multi-player one
**CONTEXT**:
I am currently developing the front-end/ client of a simple browser game using HTML5 Canvas/JavaScript. In the future, I would like to add a multi-player dimension to it, most likely using node.js/mongoDB. At this point, however, I have no experience whatsoever with the required back-end technologies.

**DESIRED OUTCOME**:
The game involves some simple interactions (e.g. collect a key; once you've collected it, you can open the door, etc.). In the multi-player mode, the outcomes of said interactions carried out by any player are supposed to affect the game state for all players (e.g. if any player has opened the door, it stays open for all players). This will likely require setting up a database.

**QUESTION:**
At what point do I need to start writing the code in a way which involves referencing a database?
Does it make any sense at all to first develop the "game logic" in JavaScript only (as if it was only meant to be played as a single player) and only afterwards proceed to rewriting the code referencing a database?

Apologies if my question sounds idiotic. Newbie here!

# Answer
> 1 votes
Turning a game developed for singleplayer into a multiplayer game when it was not designed for that from the start can be extremely difficult, both regarding software architecture and regarding game design.

But there are some things you can do which make it much easier to add multiplayer later while not hampering your development progress too much while you are still single-player.

## Software Architecture

The most important is having a clear separation of concerns from the start. Strongly encapsulate the input, game mechanics, game state, graphic engine and UI of your game. Have them communicate with each other using clearly defined, loosely coupled functions which assume nothing about the inner workings of the other modules.

This allows you to later replace these local modules with remote modules which then communicate with the remaining local modules using the same functions you already have.

* When a second local player joins the game, you simply create a new instance of the input module which listens to different keys and assign it to a new instance of the player entity.
* When a new remote player joins the game, then a network input module takes the role of the local input module.
* When you move game mechanics to a server, then the server networking module takes the role of a local gameplay module.
* To send local events to the server, you could either add a second consumer to your input module or use the same functions which are used by the UI module to monitor changes in the game state.

You might also go a step further and develop your singleplayer game as if it were a multiplayer game. Assume every game entity is remote-controlled, but "fake" that remote control with a local controller. That way most of your game architecture won't know and won't care if a game entity is an enemy controlled by a local AI controller or another player controlled by a network controller.

And besides, proper encapsulation and separation of concerns is always a good guideline for a clear and easily maintainable and extensible software architecture.

## Game Mechanics

But besides the architectural concerns, there are also game design concerns. Multiplayer games are often far harder to design than single player games for a couple reasons:

* **Game balance** is more important. When you accidentally have a feature in your game which is so overpowered that it breaks the game, then single-players will often be able to show at least some restraint from abusing it until it stops the game from being fun. You might also see players trying to finish the game without using that overpowered feature as a self-imposed challenge. In multiplayer, however, players will have far less quarrels. Competitive multiplayers will usually do everything it takes to win, even if it makes the game boring to play for everyone including themselves.
* **Counter play** becomes an important consideration. When you give the player a new ability in a single-player game, you just have to wonder "How does this make the game more fun for *the user*?". But in a multiplayer game you also have to wonder "How does this make the game more fun for *the one it is used against*?". For example, freezing an enemy in a block of ice for a couple minutes might be fun in single-player, but in multi-player it is extremely annoying for the one being frozen and unable to play. Extra Credits made a good video about this topic.
* **Time skipping** becomes impossible. In a single player game you can skip boring sequences by either speeding up time (common in strategy and puzzle games) or by simply omitting them (fast-travel systems are a common example). However, when multiple players share the same game world, they also share the same game time. You can usually not speed up the game for *some* players who are currently in a boring phase but not for those who are currently in a more complex game phase.

Again, the best way to address these problems early is to design your single-player game as if it were a multiplayer game. To address balance and counter-play, consider to follow a general rule that whatever the player can do can also be done by the AI opponents. And if you notice that parts of your game are boring and tedious, don't take the easy way out by simply using time-skipping. Try to find a proper solution to make those phases as interesting as the rest of the game or to speed them up in a way which is plausible within the fiction of the game and does not break game balance in multiplayer.

## Narration

There are also narrative differences between single player and multiplayer. In single player, the player-character (PC) can be someone special. There is no issue with making the PC the chosen Mary Sue character the whole world turns around. But the more players you add, the more limited you become regarding the role of the PC in your game's narration. In a multiplayer game, the PCs have to share the spotlight with each other. Not everyone can be "the chosen one".

In a massive multiplayer game where you have *thousands* of PCs, it becomes almost impossible to add any convincing narrative which makes the PC and their experience seem unique. Some MMO games *try* by having those quests of the game designed to be played alone make the PC somehow special, hoping that the player ignores the fact that all the people around them currently experience the exact same story they do. But the illusion falls apart as soon as you enter the cooperative content.

But in exchange for that, you get a completely different narrative angle. You can give the player the feeling of being part of something greater and making a useful contribution to a coordinated group effort. This is challenging (but not impossible) to pull off in a single-player game due to the lack of empathy for the NPC characters, but it can be a very satisfying experience in a massive multiplayer game where the player knows that all those people they fight alongside are in fact real humans.

# Answer
> 0 votes
Knowing the technologies you are going to use for the network layer is usually a big advantage so you don't write your whole game in a certain way, and find out 40% needs to be rewritten to adjust to the network technology you will be working with.

For a multiplayer you are surely going to need to work with Sockets, for real time communication.

# Answer
> 0 votes
I think Philipp has covered the main architectural concerns.

Just one more point I'd like to add is to plan for your game actions to resolve asynchronously.

Imagine we write the local version of the "spend key to unlock door" interaction something like this:

```
function UseKey(door) {
   if(door.isLocked == false)
       return false;

   door.Unlock();
   inventory.remove(key);
   return true;
}

```

If we port that to a multiplayer form naively, we could have two players each try to unlock the door at the same time, before either one has gotten the message that the door is already unlocked. So they both consume their keys for just one door unlocking — or you need more complicated reconciliation logic to detect this conflict and roll back the consequences to give back one of the keys after the fact.

Instead you'll want your game actions to take some form of "request & confirm" form, where using the key just sends a signal to the \[local or server\] door authority that you intend to unlock it, but doesn't immediately alter your game state. Then you have some kind of event or callback that can happen after the initial use interaction has returned, which actually confirms whether the interaction succeeded and applies the consequences to your game state.

Setting up even your local/single-player version of the game to work this way will make it much easier when you later want to replace the local gameplay logic with a server authority, without massive structural changes to every action that could result in a conflict with other players, or cheating with a hacked client.

# Answer
> 0 votes
In this case (as I did) you need to move all you game mechanic to backend. Not a big deal with NodeJS. And develop your wrapper for WebSocket to provide auth and way you will communicate between clients and server (as your client is browser - "you can't trust anyone).

Client in this case only do what server say.

UPD: Think careful about communication protocol. Constant parsing JSON is not good idea. For example you can separate variables in message with non-print character.

# Answer
> -2 votes
I would say there's no real need to think about it right now, just implement the game client-side but make sure to keep the core 'rules' decoupled from the rest of the code.

Reason 1 would be from a purely architectural standpoint, you don't want your client-side code to be too coupled to your rendering code and you won't want the server code too coupled to the database, so it should be written to be flexible anyway.

Reason 2 - if you end up going with Node for the backend (which I recommend), the game logic can be very similar -- you could even share the 'rules' module across the client and the server -- because the environments (Node and the browser) are both event-driven and Node allows you to have variables that persist between requests (as opposed to, for example, PHP where everything would have to be loaded from the database on each request).

See the code behind meteorchess.com for an example of this being done: lightsquare (client), lightsquared (server) and chess (chess rules module used unaltered by both). In this app, the database (Mongo) is only used for archiving the games once finished. While in-play, the games are just in memory on the server.

---
Tags: javascript, node.js, html5, mongodb
---


title: How does Admob pay for banner ads?

text:
# Question
Title: How does Admob pay for banner ads?
I want to know how Admob pays for banners? Is it based on time or impressions or count of times that been showed to users?

# Answer
Admob, like most ad services, computes your earnings based on *impressions* (a user saw an ad) and/or *clicks* (a user clicked on the ad).

Admob uses an auction model, so the actual monetary value (to you) of a given impression or click isn't fixed and will depend on what the people buying the ads have bid for the space. Admob will attempt to display the type of ad that results in the most revenue for you.

You can view historical trends regarding your earnings in your control panel, along with a variety of reports and metrics that may help you estimate the future revenue for your ad campaigns.
> 2 votes

---
Tags: advertisements, admob
---


# Question
Title: What debugging info should I put in the "About" box
I'm developing an Android game with the idea of publishing it, and I wonder what info should I put in the "About" dialog that many main menus have.

The idea is to make bug report and debugging easier. Users can click in the "About" box and read the details of their device, and include them in any bug report they send me - I know Google sends relevant device data to the developer when there's a crash, but I'm thinking in bugs that not necessarily end with an abnormal program termination.

So far, I've added API number of device, screen size, screen density, and number of processors.

My current "About" screen is something like this:

> Game title
> Game icon
> **API version**
> **Screen size**
> **Screen density**
> **Number of processors** (just in case, because game uses threading)
> Game version number
> Developer e-mail
> Copyright information

If anyone has experience publishing and maintaining an app, specially in Android, I want to know what can I add there to make user reporting and debugging easier.

# Answer
Diagnostic information (whether or not you put it in the About box or somewhere else) is largely up to you and your ability to process it. You should include diagnostics information that *you know* can help you track down issues.

Basic hardware statistics about the machine (RAM, GPU type, CPU speed), for example, are probably something you'd know how to figure into your calculations for a particular problem a user is reporting.

The color of the LED running lights in the machine, though? Probably less useful. Including too much information, especially information you don't yourself know what to do with, just creates noise for you to sift through.

Note that you should be careful including anything that could be considered "personally identifying" in your reports. There could be legal issues involved in doing so, and even when you're in the clear users may find it offensive unless you're very clear about what you are collecting, when you actually send it back to yourself, and why you're doing it.
> 2 votes

---
Tags: android, debugging
---


title: Java - Collision detection (Glitch)

text:
# Question
Title: Java - Collision detection (Glitch)
I am working on a platformer game for the final year project in HS. However... The collision detection system I use is basically about checking wether a specific part of the character intersects with another block or not.

The collision seems to be working fine except that it causes some bugs such as player king of getting stuck or slowing down when hitting from the sides or gets thrown up when both upper and \< or \> keys are used.

**My question is; How can I improve the collision code in order to avoid such glitches and have sort of 'slippery' collisions?**

here is a preview of how the bounds look

and here is a preview of what it actually looks like in game (click for better quality)
The code i use for collision detection: (tempObject are blocks that the player is intersecting with)

```
if(getBoundsTop().intersects(tempObject.getBoundsBottom())){
    y = tempObject.getY() + height;
    velY = 0;
    System.out.println("Top collision");
}

if(getBoundsBottom().intersects(tempObject.getBoundsTop())){
    y = tempObject.getY() - height;
    velY = 0;
    falling = false;
    jumping = false;
    //isOnBlock = true;
} else {
    falling = true;
    //isOnBlock = false;
}

if(getBoundsRight().intersects(tempObject.getBoundsLeft())){
    x = tempObject.getX() - this.width;
}

if(getBoundsLeft().intersects(tempObject.getBoundsRight())){
    x = tempObject.getX() + this.width;
}

```

and here is are the bound methods:

```
public Rectangle getBounds() { return new Rectangle( (int)x, (int)y, (int)width, (int)height ); }

    public Rectangle getBoundsTop() {
        return new Rectangle(
                (int)x,
                (int)y,
                (int)(width-(width*0.01f)),
                (int)(height/2)
        );
    }
    public Rectangle getBoundsBottom() {
        return new Rectangle(
                (int)x,
                (int)(y+(height/2)),
                (int)(width-(width*0.01f)),
                (int)(height/2)
        );
    }

    public Rectangle getBoundsLeft() {
        return new Rectangle(
                (int)x,
                (int)y,
                (int)((int)width*0.15f),
                (int)height
        );
    }

    public Rectangle getBoundsRight() {
        return new Rectangle(
                (int)
                ((int)x+(width-(width*0.15f))),
                (int)y,
                (int) ((int)width*0.15f),
                (int)height
        );
    }

```

# Answer
I actually had the same problems many years ago when implementing collision detection in Java for my final year project (what a coincidence!). What I did to solve it was to inset the collision boxes by, say, 10% in either direction like so:

The whole image represents the player. The *yellow* boxes represent vertical collision detection (up / down), the *blue* boxes represent horizontal collision detection (left / right) and the *red* areas mark "deadzones" where there is no collision detection.

This will solve the problem where you collide from the side, but the game thinks you've hit the top box so it pushes you down etc. You might have to play with the percentage to inset the boxes since it will change depending on how far your character can reasonably penetrate a surface (so if your player might move 10px inside a surface before collision steps in, inset the sides by 10px in either direction).
> 1 votes

# Answer
i think you are adding the movement or gravity every thick were you are calculating the position, to make better collisions you have to:

update()

```
{
 1-move the sprite ( gravity moves the sprite down as well )
 2-check for collision and get the overlapped value
   NOTE: check step 2 with X & Y axis
 3-move back the overlapped value ( so you wont see the sprite going back )
}

```

here is the function im using:

```
     /**
 * checks if there is a collision between sprite 1 and certain coordinate
 * and check if the sprite mush be pushed the other or if it must bounce
 *
 * @param s1
 * @param x
 * @param y
 * @param width
 * @param height
 * @return true if there is a colision and false if not
 *
 * */
public String blockRectangle(Sprite s1,int x, int y, int width,int height)
{
        int halfWidth = width / 2;
        int halfHeigth = height / 2;
        int centerX = x + halfWidth;
        int centerY = y + halfHeigth;

    String side=Config.COLISION_NONE;

            //get distance vectors
    float vx=s1.getCenterX()-centerX;
    float vy=s1.getCenterY()-centerY;

    float combinedHalfWidth = s1.getHalfWidth()+halfWidth;
    float combinedHalfHeight = s1.getHalfHeight()+halfHeigth;

            //collision on x axis
            if(Math.abs(vx) < combinedHalfWidth)
    {
                //collision on y axis
        if(Math.abs(vy) < combinedHalfHeight)
        {

                        //collision made

            float overlapX=combinedHalfWidth-Math.abs(vx);
            float overlapY=combinedHalfHeight-Math.abs(vy);

                        if( overlapX < overlapY )
                                {

                if( vx > 0 )
                {
                                        s1.setX( s1.getX()+overlapX );
                                        return Config.COLISION_LEFT;
                }
                else
                {
                                        s1.setX( s1.getX()-overlapX );
                                        return Config.COLISION_RIGHT;
                }

                                }//
                            else

            {

                                if( vy > 0 )
                {
                                        s1.setY( s1.getY()+overlapY );
                                        return Config.COLISION_TOP;
                                    }
                                else
                {
                                       s1.setY( s1.getY()  - overlapY );
                                        return Config.COLISION_BOTTOM;
                }

            }

        }//height

    }//width

    return side;

}//colision con rectangulos, pero

```
> 0 votes

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


# Question
Title: How can I make Iridescence material In unity?
One of the characters of the Dota2 that Is called Nyx Assassin has an interesting material effect If you look at the body and feet you can see this effect.It looks like poily/polluted water.I like to know how can I make something like that In unity.

# Answer
I found same question here and I could make Iridecence In unity .

you can download this shader from my github.

My tutorial About Iridescence Shader

> Iridescence (also known as goniochromism) is the phenomenon of certain surfaces that appear to gradually change colour as the angle of view or the angle of illumination changes. Examples of iridescence include soap bubbles, butterfly wings and seashells, as well as certain minerals. It is often created by structural coloration (microstructures that interfere with light). https://en.wikipedia.org/wiki/Iridescence

# Prototyping with Blender

# Simple Iridescence Shader

# Adding distortion to Iridescence
> 2 votes

---
Tags: unity, shaders, materials
---


title: Is Rigidbody a variable type?

text:
# Question
Title: Is Rigidbody a variable type?
I been searching for this for a while online but found no good answer so now I'm asking here. I have a scripting question about Unity's Rigidbody.

When your making a game object move with Rigidbody you typically make a script for it that starts off with

```
public Rigidbody rigid;

```

Then you put in a `GetComponent` call like so

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

```

And the part I don't understand is how the Rigidbody variable works. Is it a variable type that unity is using cause even in the GetComponent it starts looking for Rigidbody not rigid. That seems like making a int variable then calling it saying Debug.Log(Int);

Also in unity script from the documentations it uses

```
function Start () {
  var rb = GetComponent.<Rigidbody>();
}

```

Theres no Rigidbody in the declaration of the variable at all. Thats what made it even more confusing for me due to how GetComponent cleary shows it getting just the Rigidbody component but from the look of the script how does it connect to the game object?

With the C# example you drag and drop the GameObject in the Rigidbody variable even when the script is connected.

---

The reason why I'm asking is because I'm wanting to learn intuitively where I understand all the meaning of code like a second language. Is that normal?

# Answer
Yes, `Rigidbody` is a type.

You have three different code snippets in your question, and they have three different explanations.

First, you have `public Rigidbody rigid;` This is a *declaration* of a variable. The variable's *name* is `rigid`, and the variable's *type* is `Rigidbody`. The type is what determines what that object can do, how it will behave. The name is simply what you call it when you refer to it.

Second, you have

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

```

Here, you're calling the `GetComponent()` function to find a component, and assigning the *result* to the `rigid` variable (because that's what you named it, above). The `<Rigidbody>` bit is an indication that this function call is a C# concept called a generic method.

Generics are often used as way to write code when you don't know the *precise* types that would be involved. As a side-effect, they can also be used the way they are here in `GetComponent`, as a way to require you to specify a type parameter in a function call. This ensures that `GetComponent` both

* knows what kind of component to go search for and
* returns that component in a fashion that allows you to assign it to a variable of the desired type (`Rigidbody`) safely.

`GetComponent` actually looks like `T GetComponent<T>()`; the type of its return value is the same type you tell it about inside the angle brackets. That's why it can be correctly assigned to the variable `rigid` since they both are of the same type.

Finally, you've got:

```
function Start () {
  var rb = GetComponent.<Rigidbody>();
}

```

This code isn't C#, it's Javascript. It is doing essentially the same thing as the second snippet, just with different syntax because it's a different language. It's possible you're confused because `var` is also a keyword in C#, where is serves as an indication that the type of the variable should be deduced by the compiler.

If you're unfamiliar with the C# programming language, you might find MSDN's interactive tutorial informative. It can help give you some experience with C# concepts outside of Unity, which may aid in your pursuits.
> 1 votes

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