# Question
Title: What would be the best approach to creating a pressure plate in a 2D game?
I've just really gotten started in Unity and while documentation has been helpful I haven't figure out how to detect collisions with 2 or more objects. I was able to get a script working that plays a sound when I touch the pressure plate with the player but I don't know how I would do something when 2 objects are within the collider but undo it when one of them leaves the area.

```
void OnTriggerEnter2D(Collider2D other)
{
    if(other.tag == "Player")
    {

        AudioSource.PlayClipAtPoint(Sound, transform.position);
    }

}
}

```

Am I going about this the wrong way by using OnTriggerEnter2D? I see that there is a mass component on Rigidbodies but I don't know if I should be using it because I am still a novice in Unity. I'm also aware of OnCollisionExit but I don't think that works in this case because I'm currently only detecting 1 object but I need to detect 2. I was able to find videos that somewhat helped but all of them only worked with one object and were in a 3D space rather than a 2d one.

# Answer
Let's first declare a variable to store the number of players currently standing/colliding with the platform.

In this case we want two players to activate the platform; Unity gives us 3 main functions to check whether an object collided with another object: OnTriggerEnter, OnTriggerStay and OnTriggerExit.

In this case we are working with 2 dimensions, so we are going to use the *2D* versions of these functions.

We specifically want to check whether our players are *both* colliding with the object's collider; (In the pseudo script i attached below, I am assuming you tagged your first player `Player1` and your second one `Player2`)

We are going to use the `OnTriggerEnter2D()` function, (which takes in as parameter the object the platform is colliding with) to increment the player count variable by 1, if either one of our players is inside the trigger area;

Once either one of them gets out the trigger area, `playerCount` gets decremented by one, to a total of 0, if both players have gone out the trigger area.

***PseudoScript***

```
int playerCount = 0;

void OnTriggerEnter2D(Collider2D other)
{
     if(playerCount < 2)
   {
       if(other.tag == "Player" || other.tag == "Player2")
       {
          playerCount++;
       }
    }

   else
   {
       OnState();
   }
}

void OnTriggerExit2D(Collider2D other)
{
   if(playerCount > 0)
   {
       if(other.tag == "Player" || other.tag == "Player2")
       {
          playerCount--;
       }
    }

   else
   {
       OffState();
   }
}

```
> 4 votes

# Answer
As you can see on the execution order diagram, the engine will first execute all `FixedUpdate` methods, then all `OnTriggerXXX` methods and then all `Update` methods.

That means you can have a player count for your pressure plate which has

1. A `FixedUpdate()` method which resets the count to 0
2. A `OnTriggerStay(Collider other)` method which increases the count by 1 everytime it is called with an `other` collider which belongs to a player
3. A `Update` method which checks the count and acts appropriately.

---

A completely different approach you could use would be to use the Unity physics engine and implement your pressure plate like an actual, physical pressure plate.

1. Assign non-kinematic, gravity-affected rigidbodies to the characters and the pressure plate.
2. Place the pressure plate slightly above the ground
3. Use a spring joint between pressure plate and floor so that the pressure plate resists forces.
4. Restrict the movement- and rotation axis\` of the plate's rigidbody so it can only move up and down.
5. Add a trigger-collider below the pressure plate which detects if the plate moves down.
6. Calibrate the spring strength and the player mass so that the weight of two players moves it into the trigger collider but the weight of one player does not.

However, I would only recommend this solution if you are creating a game which is supposed to have realistic physics and you are already making use of the physics engine. Also keep in mind that crafty players might find alternative methods to add enough force to the pressure plate to trigger it. Whether this is good or bad depends on your game.
> 6 votes

# Answer
When working with colliders in Unity, remember that trigger and collider are two different things. Do not confuse these two.

If you would like your object to react/bounce off another object, use Collider. In your case, Trigger is what yo should be using. So ensure IsTrigger is enabled on the pressure plate.

You must also ensure at least one GameObject, either the pressure plate, or the player and other object you wish to detect, has a Rigidbody2D attached to it.

```
private int colCount = 0;

private void OnTriggerEnter2D(Collider2D col){

switch(col.tag){
    case "Player":
    colCount++;
    break;
    case "Other Object":
    colCount++;
    break;
  }

if(colCount >= 2){
    runDetectionConditions();
  }

}

private void OnTriggerExit2D(Collider2D col){

switch(col.tag){
    case "Player":
    colCount--;
    break;
    case "Other Object":
    colCount--;
    break;
  }

}

// Run whatever conditions you would like to run, when two objects are detected on pressure plate
private void runDetectionConditions(){
Debug.Log("Two objects are being detected on collider.");
}

```
> 2 votes

# Answer
There are a lot of people here already answering in terms of using the OnTrigger calls (which could be replaced with OnCollision calls if you want to work with non-trigger colliders). However I wanted to suggest another method should you find yourself in a situation where you just want to do a quick check of what colliders are in a given area without doing a lot of setup.

Both 2D and 3D Unity have Physics functions to get one or many objects in a given location. For 2D Physics the single version is always something like Physics2D.Overlap\[shape\], while the multi version is Physics2D.Overlap\[shape\]All. For 3d Physics just drop the 2D from either of those.

For something like a pressure plate you'd be looking at something like Physics2D.OverlapAreaAll, Physics2D.OverlapBoxAll, Physics2D.OverlapCapsuleAll, or as another option possibly Physics2D.LinecastAll. These could all be placed much like your trigger is now, only through code instead of the editor.

From these you will get an array of Collider2D objects which are in the given area and on the appropriate layers (should you employ layer masking, which you should since it will throw out a lot of unnecessary checking). From there you can count, adjust, or whatever any traits you wish on the relevant GameObjects based on the results of the check.

As a side note since I see performance comments on other answers, this method will pay the detection cost for each pressure plate you have in scene that is doing the check. However, adding triggers to your scene is not free either. In either case don't worry about the performance too much until you start seeing a problem, at which point you can pull up the profiler and see what is taking too much of your time and address it.
> 1 votes

---
Tags: unity, c#, 2d, collision-detection
---


# Question
Title: Large-Scale 2D worlds with a "world texture" to draw to causing memory issues
**Background:**

I've currently implemented a world class where the dimensions are provided in meters and those dimensions are translated to pixel values for an allegro (4.x) memory bitmap to be created so objects can be draw to it. This seemed like a good idea...until I learned the hard way that world dimensions translated to pixel dimensions such that the bitmap created would be upwards of 100,000,000 pixels causes um..."issues" and allegro (4.x) barfs.

**Question:**

How would I implement large-scale worlds such that they can be any arbitrary size and still have a bitmap/surface/texture to draw to that's small enough to fit into memory along with everything else? Please limit answers to allegro 4.x solutions.

# Answer
With additional experience I've learned that what I was trying to achieve was just stupid.

The real answer is to use off-screen textures and only draw the area and entities that are visible to the camera to that off-screen texture. The very last step is to draw that texture to the backbuffer. With that, your world can be as large as you want it and it'll never cause an issue.
> 0 votes

# Answer
The problem you're running into is that 100,000,000 is a *big number* for a 32-bit floating-point value.

There are two approaches to fixing this. First, consider whether you actually need such big unit. Do you really need a world 100,000,000 pixels across? Can you consider a system where 1px == 100m or something along those lines? Simply scaling down your units is a very easy and simple solution in many cases.

If that doesn't work, consdier breaking your world up into chunks. Each chunk can be a fixed-size square of some smaller and easily handled size, say 1000x1000 meters/pixels. You can identify a position by a combination of a chunk ID (really, the 2D integer coordinates of the chunk in the world chunk map) and a position vector inside the specific chunk. You can with a little thought efficiently figure out which chunks are visible (a maximum of four at a corner if the chunks are bigger than the screen; maybe more for wider monitors/resolutions).

Going the chunk route is a good idea even with smaller worlds for various reasons, but don't discount the idea of rescaling the world if you can.

> Please limit answers to allegro 4.x solutions.

This really has nothing to do with Allegro in any way.
> 2 votes

# Answer
As Sean points out, your issue is nothing to do with Allegro, this isn't an Allegro limitation. If your texture is 10000x10000, you're talking about something over 1GB in size (10000 x 10000 x 3 bytes per pixel). If it's really 100,000,000 across, then you're talking terabytes of memory. This just simply isn't feasible, not on Allegro, not on any library. You're talking fundamental hardware limitations. And the vast majority of that texture would be unused. Blank. A waste of memory. So my gut instinct is that you're coming at whatever problem you have from the wrong angle. However vast, sparse worlds are nothing new, and there's a wealth of research out there on how to do them well. The keyword to search for is probably terrain streaming / generation.

However, to answer your question as it is: forget about Allegro for the moment, and consider the two aspects you need to solve here: density, and sparseness. Well, three if you count accuracy, but just stay well away from floating point anything (use 64-bit integers for positions / distances) and you should be fine.

If you can see all the world at once, then you're seeing it on a screen let's say 1680 x 1050. So no matter how dense your actual world data is, each pixel on screen is going to be an average of a bunch of source pixels. Even when you zoom in, it'll still be several pixels, and you've going to have to zoom in quite far before each pixel in the world data is visible on screen. So you probably want to be thinking about precalculating and storing layers, like mip-maps, for each potential level of zoom. When you're zoomed right in, you can see the data as it was originally drawn. As you zoom out, at some point you stop showing the 1:1 layer, and instead show a layer where each pixel is the average of four pixels, then sixteen, then thirty-two.

Crucially, you're never looking at an area of more than 2048 x 2048 in size - and your graphics card / library should be able to handle that. Your top level texture, the most-zoomed out level, is 2048x2048 but your entire world can fit on it. As you zoom in one level, you need 4 2048x2048 textures, one for each quadrant. Depending on where you are looking in the image, you may be looking at just 1 of those 4 textures, or you might be looking at a border between 2 or 4 of them. As you zoom in one level more, you need 16 2048 x 2048 textures to display the whole world, but crucially, you can never see more than 4 of them at any one time (your screen simply isn't big enough). So you can pick and choose which 4 to be loaded based on where you are looking. This is the key to the whole thing - by breaking up your world into chunks and levels, you can selectively load parts of it.

This feeds into the sparseness aspect. At the most zoomed in level, your real data is just a matrix of 2048 x 2048 textures. Given a coordinate in your 2D world, you can map it to which texture contains the data for it by simply dividing the coordinates by 2048 (e.g. \<5000, 2000\> is in cell \<2, 0\>). If the content is being drawn onto the world data by users, most of it will start empty. And if it's empty, you can avoid having to store anything for it at all. When the users try to paint into a cell that hasn't been created yet, just make a new 2048x2048 texture for that cell, and let them paint into that.

Bear in mind the more zoomed-out levels can be generated automatically from the high detail, zoomed-in layer. Only the zoomed-in layer has real data in it. When you have to generate the zoomed out layers, you can simply assume that any chunks that didn't have anything painted in them remain at their default colour (white, or green, or transparent, whatever).

As users change values in the zoomed in cells, sections of the layers above them will have to change to reflect that. Change an entire cell at the fully zoomed in from white to black, and a quarter of the cell in the layer above would change, a sixteenth of the cell in the layer above that, and so on; once you get to the top level you'd probably barely notice the tiny shift in colour of one pixel. But you can imagine this to be the effect you'd get of painting the roof of your house black instead of white, you might see it from a helicopter, but you wouldn't be able to see it from space.
> 1 votes

---
Tags: c++, allegro
---


# Question
Title: How to get a camera's frustum information?
I have a local coordinate system with three camera normalised directions, `D`, `U` and `R`.

I also have the following information:

```
camera_location
lookat_point
up_direction
distance_near_plane
distance_back_plane
fov
aspect_ratio

```

With this I'm trying to get the information regarding the camera's frustum, the coordinates of it's 8 vertices and the 6 planes that make it up. How do I do it?

# Answer
> 1 votes
One way would be to construct the projection matrix from your info, invert it, and send the 8 device-normalized coordinates of the corners through it. In OpenGL (and I assume Vulkan), those would be:

```
(-1, -1, -1),
(-1, -1, 1),
(-1, 1, -1),
(-1, 1, 1),
(1, -1, -1),
(1, -1, 1),
(1, 1, -1),
(1, 1, 1)

```

In DirectX or Metal, the Z values should be 0 and 1 rather than -1 and 1.

---
Tags: camera, frustum
---


# Question
Title: Unity - Display array of Objects in inspector
I have an array of `ScritableObject`'s, which should only be displayed in the inspector if a `boolean` is true. How would I do this? With my current code, I get an error saying:

> Cannot implicitly convert type `Tile` to \`Tile\[\]

This is my current code:

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

[CreateAssetMenu (fileName="Data", menuName="Tiles/Map", order=1)]
public class Tile : ScriptableObject {

    public ETile eTile;
    public Sprite sprite;

    [Space(5), Header("Variety")]
    public bool variety;

    [Range(0f, 1f)]
    public float varietyChance;
    public Tile[] varietyTiles; <---- This should be hidden if variety is true
}

public enum ETile {
    Water,
    Grass
}

[CustomEditor(typeof(Tile))]
public class MyScriptEditor : Editor {

    override public void OnInspectorGUI() {
        var tile = target as Tile;

        tile.variety = EditorGUILayout.Toggle("Hide Fields", tile.variety);

        if (tile.variety) {
            tile.varietyTiles = (Tile)EditorGUILayout.ObjectField("Tile", tile, typeof(Tile), allowSceneObjects: true);         }
        }
    }
}

```

# Answer
Found it, small modification to Tim C. The line:

```
EditorGUILayout.PropertyField(tileProperty, includeChildren:true)

```

Would in this case always return `false`, therefor the if-statement is never run, which makes that the `ApplyModifiedProperties` method of the `serializedObject` is never called. Making that the value of the new property is never stored in the `tile.varietyTiles`. Therefor, the correct code would be:

```
tile.variety = EditorGUILayout.Toggle("Enable", tile.variety);
if (tile.variety) {
    SerializedProperty tileProperty = serializedObject.FindProperty("varietyTiles");
    EditorGUILayout.PropertyField(tileProperty, includeChildren: true);
    if(tileProperty.hasChildren)
    {
        serializedObject.ApplyModifiedProperties();
    }
}

```

**Explanation**

This code first checks whether you want to display the property or not. After that, on line 3 and 4, it receives the value of the current property and generates a new property with the values of the old one. In the if-statement, it's check whether and `tileProperty` contains children. If `true`, the value of the `tile.varietyTiles` is updated with the new content of `tileProperty`.
> 1 votes

# Answer
You can't do this with ObjectField because Arrays are not Objects. You need to use a PropertyField instead of an ObjectField, which is more generic and can handle properties of any type.

Corrected code:

```
[CustomEditor(typeof(MyTile))]
public class MyScriptEditor : Editor
{

    override public void OnInspectorGUI()
    {
        var tile = target as MyTile;

        tile.variety = EditorGUILayout.Toggle("Hide Fields", tile.variety);

        if (tile.variety)
        {
            SerializedProperty tileProperty = serializedObject.FindProperty("varietyTiles");
            if(EditorGUILayout.PropertyField(tileProperty, includeChildren:true))
            {
                serializedObject.ApplyModifiedProperties();
            }
        }
    }
}

```
> 0 votes

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


title: DirectX 11 - Depth Stencil not working

text:
# Question
Title: DirectX 11 - Depth Stencil not working
I'm currently working on a game for university in DirectX 11.

I have tried to add in a depth buffer to my project, but since adding it in none of my objects show.

```
//Describe the Depth/Stencil Buffer
D3D11_TEXTURE2D_DESC db;
db.Width = Width;
db.Height = Height;
db.MipLevels = 1;
db.ArraySize = 1;
db.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
db.SampleDesc.Count = 1;
db.SampleDesc.Quality = 0;
db.Usage = D3D11_USAGE_DEFAULT;
db.BindFlags = D3D11_BIND_DEPTH_STENCIL;
db.CPUAccessFlags = 0;
db.MiscFlags = 0;

//Create Depth View
hr = g_pd3dDevice->CreateTexture2D(&db, NULL, &g_depthBuffer);
if (FAILED(hr)) {
    MessageBox(NULL, L"Error.", L"Error", MB_OK);
}
g_pd3dDevice->CreateDepthStencilView(g_depthBuffer, NULL, &g_depthView);
//g_pd3dDevice->CreateDepthStencilState(&db, &g_depthStencil); //When uncommented, the '&db' shows the following error.
//argument of type "D3D11_TEXTURE2D_DESC*" is incompatible with parameter of type "const D3D11_DEPTH_STENCIL_DESC*"

//Set Render Target
g_pImmediateContext->OMSetRenderTargets( 1, &g_pRenderTargetView, g_depthView );

```

---

```
    void Render()
{
    //Update our time
    static float t = 0.0f;
    if ( g_driverType == D3D_DRIVER_TYPE_REFERENCE )
    {
        t += ( float )XM_PI * 0.0125f;
    }
    else
    {
        static ULONGLONG timeStart = 0;
        ULONGLONG timeCur = GetTickCount64();
        if (timeStart == 0)
            timeStart = timeCur;
        t = (timeCur - timeStart) / 1000.0f;
    }

    //
    // Animate the cube
    //
    //g_World = XMMatrixRotationY( t );

    //
    // Clear the back buffer
    //
    g_pImmediateContext->ClearRenderTargetView( g_pRenderTargetView, Colors::MidnightBlue );
    //g_pImmediateContext->ClearDepthStencilView( g_depthView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0 );

    //
    // Update variables
    //
    ConstantBuffer cb;
        //cb.mWorld = cube1;
    cb.mWorld = XMMatrixTranspose( cube1 );

    cb.mView = XMMatrixTranspose( g_View );
    cb.mProjection = XMMatrixTranspose( g_Projection );
    g_pImmediateContext->UpdateSubresource( g_pConstantBuffer, 0, nullptr, &cb, 0, 0 );

    //
    // Draws first square
    //

    g_pImmediateContext->VSSetShader(g_pVertexShader, nullptr, 0);
    g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer);
    g_pImmediateContext->PSSetShader(g_pPixelShader, nullptr, 0);
    g_pImmediateContext->DrawIndexed(36, 0, 0); //36 vertices needed for 12 triangles in a triangle list

    ConstantBuffer cb2;
        //cb2.mWorld = cube2;
    cb2.mWorld = XMMatrixTranspose(cube2);

    cb2.mView = XMMatrixTranspose(g_View);
    cb2.mProjection = XMMatrixTranspose(g_Projection);
    g_pImmediateContext->UpdateSubresource(g_pConstantBuffer, 0, nullptr, &cb2, 0, 0);

//  g_pImmediateContext->VSSetShader(g_pVertexShader, nullptr, 0);
//  g_pImmediateContext->VSSetConstantBuffers(0, 1, &g_pConstantBuffer);
//  g_pImmediateContext->PSSetShader(g_pPixelShader, nullptr, 0);
    g_pImmediateContext->DrawIndexed(36, 0, 0);

    //cube1 = XMMatrixIdentity();

    //
    // Present our back buffer to our front buffer
    //
    g_pSwapChain->Present( 0, 0 );
}

void Update()
{
    rot += 0.0005f;
    if (rot > 6.26f)
        rot = 0.0f;

    cube1 = XMMatrixIdentity();

    XMVECTOR rotaxis = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
    Rotation = XMMatrixRotationAxis(rotaxis, rot);
    Translation = XMMatrixTranslation(1.0f, 1.0f, 0.0f);

    cube1 = Translation * Rotation;

    cube2 = XMMatrixIdentity();

    Rotation = XMMatrixRotationAxis(rotaxis, -rot);
    Scale = XMMatrixScaling(0.5f, 0.5f, 0.5f);

    cube2 = Scale;
}

```

From what someone else had mentioned, that I'm either not creating a D3D11DepthStencilState or not clearing the depth stencil view. I've tried to fix the problem, but no luck so far.

# Answer
It is important how you create the depth stencil state and what values you clear the depth buffer to. And you should always clear the depth buffer at least once per frame if you are writing to it (for optimal hardware behaviour).

I would try setting a depth stencil state where Depth is disabled, that should set you back to working state (if your app works when no depth buffer is bound). Then you can enable the depth test/depth write and see where it goes wrong. Also take note of your DepthFunc. The depthFunc should be generally COMPARISON\_LESS\_EQUAL if you are clearing your depth buffer to 1.0f, and GREATER\_EQUAL if you are clearing to 0.0f values.

Also, you projection matrix near and far planes matter. If nearPlane \< farPlane, then you should clear depth buffer to 1.0f. If farPlane \< nearPlane, then clear to 0.0f.

Also, always enable debug layer (D3D11\_CREATE\_DEVICE\_DEBUG) when looking for DirectX bugs. And try to use a graphics debugger, like the one built into visual studio, RenderDoc, or Nvidia Nsight.

Good luck!
> 1 votes

---
Tags: c++, directx11
---


# Question
Title: Organizing objects into groups of 20. C#
I am building a game where players can build their own airplanes and fly them around. When the vehicle is spawned, all the buildables used to construct the airplane should be placed into groups of 20 to be merged as a submesh to the airplane. When one of the buildables is hit by a projectile and is destroyed, the mesh is reloaded, this time without the buildable that was hit creating the illusion that it was destroyed.

I have a few scripts

Airplane Core:

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

[System.Serializable]
public class AirplaneCore : MonoBehaviour {

    public GameObject airplaneCore;
    public List<AirplaneBuildable> buildables;
    public List<AirplaneChunk> chunks;

    void Start () {
        AirplaneChunk[] airplaneChunks = airplaneCore.GetComponentsInChildren<AirplaneChunk> ();
        foreach (AirplaneChunk chunk in airplaneChunks) {
            chunks.Add (chunk);
        }
    }
}

```

AirplaneBuildable:

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

[System.Serializable]
public class AirplaneBuildable {
    public string buildableName;
    public GameObject buildableObject;
    public GameObject buildableNormalPrefab, buildableEditorPrefab, buildablePreviewPrefab;
    public Vector3 pos, rot;
    public bool destroyed = false;
    public float health = 100f, maxHealth = 100f;
}

```

And Airplane Chunk:

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

[System.Serializable]
public class AirplaneChunk : MonoBehaviour {
    public List<AirplaneBuildable> buildablesInChunk;
}

```

Anyone know a way I can take the buildables from AirplaneCore and place them in groups of 20 and assign each group to an AirplaneChunk's buildablesInChunk list?

For those who don't know, the gameobjects that are in the AirplaneBuilder script are: -Buildable Object: The actual object representing the component that was placed on the airplane. -Buildable Normal Prefab: The buildable that is spawned when spawning the plane. -Buildable Editor Prefab: The buildable that appears on the airplane in the vehicle builder editor. -Buildable Preview Prefab: Is simply a preview of the buildable and shows what it will look like when placed on the airplane.

# Answer
> 1 votes
To make it in a generic way, there must be a logical conversion from `List<AirplaneBuildable>` to `AirplaneChunk`. Therefore I create an abstract base class

```
public abstract class Chunk<T> : MonoBehaviour
{
    public List<T> BuildablesChunk { get; set; }
}

```

`AirplaneChunk` is now redefined as

```
[System.Serializable]
public class AirplaneChunk : Chunk<AirplaneBuildable>
{
}

```

Instead of having a fixed typed `List<AirplaneBuildable> buildablesInChunk` field, it has now a `List<AirplaneBuildable> BuildablesChunk` property (a field would work as well, if you prefer) resulting from a generic type argument.

Now we can implement the chunking as

```
TChunk[] GetComponentsInChildren<TSource, TChunk>(IList<TSource> source)
    where TChunk : Chunk<TSource>, new()
{
    const int ChunkSize = 20;

    int numberOfChunks = (source.Count + ChunkSize - 1) / ChunkSize;
    var chunks = new TChunk[numberOfChunks];
    for (int i = 0; i < numberOfChunks; i++) {
        List<TSource> batch = source.Skip(i * ChunkSize).Take(ChunkSize).ToList();
        var chunk = new TChunk { BuildablesChunk = batch };
        chunks[i] = chunk;
    }

    return chunks;
}

```

And can call it with

```
AirplaneChunk[] airplaneChunks =
    GetComponentsInChildren<AirplaneBuildable, AirplaneChunk>(buildables);
chunks.AddRange(airplaneChunks);

```

Note that we need two type parameters, as we cannot infer the chunk type (`AirplaneChunk`) from (`AirplaneBuildable`). You could have several classes deriving from `Chunk<AirplaneBuildable>`. C# has no way of knowing which one you meant.

We also need generic type constraints (`where TChunk : Chunk<TSource>, new()`). Basically `Chunk<TSource>` says: we have a type having a `List<T> BuildablesChunk` property we can assign the result to. And `new()` says: `TChunk` must have a default constructor.

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


# Question
Title: Standard decibel range for sound effects/music?
Is there a standard for a decibel range of sound effects and music in games?

I've been getting sound effects from various sources and some are much louder than others so I've had to adjust them with Audacity to be closer in volume.

Of course the user can just adjust their volume up or down if it's too loud/quiet but I'd prefer that my game's audio be in the same range as other games

(Note: specifically I'm asking for iOS/mobile games but this could apply to other systems)

# Answer
> 2 votes
There's no easy answer. Just use your ears and adjust to suit.

Computer audio formats allow you to reduce the volume of your audio clip but they cannot be increased indefinitely. Typically the digital encoding used is PCM, and there's only so far you can push the amplitude before the peaks get clipped.

In visual terms, when you see a waveform in say Audacity like this:

The left half is unamplified, the right half is amplified past the admissible range, so that its peaks are clipped. When this happens, it's also known as compression or distortion. Sometimes this is desired, mostly it's not. In addition to making things sound loud, the compression also makes it sound like coming out of a walkie-talkie. Those sharp edges where the waveforms get clipped is what makes it sound so harsh.

In Audacity, you can use the **Normalize** tool to automatically amplify so that the peaks reach maximum, without clipping.

However, there are ways to make things *sound* louder without actually making the peaks higher. This is done all the time in what's known as the loudness war. Instead of amplifying everything an equal proportion, the quieter parts are amplified more than the loud parts, so that there is minimal clipping, but the average amplitude of the entire sound is increased, and it sounds louder.

You can see an example above; the top clip is the bottom clip but **compressed**. In Audacity you can use the **Compressor** tool to do exactly this. You may need to do this to make quiet clips sound louder, even though they have been normalised, because they have a high dynamic range.

Of course, you could go the other way too; some clips may sound too loud, possibly because they were compressed. You can reduce their amplitude, or even better, find higher quality clips that were not excessively compressed.

Finally, you probably don't want your sound clips to have the same loudness in the first place. You want some clips to naturally sound louder than others, and it's better to apply this in the sounds themselves rather than your audio player's volume setting. For example, louder guns feel more powerful even if their stats suggest otherwise.

So there's no simple approach to getting sounds right. Play it by ear, listen to sounds both in isolation and as part of an overall mix, and adjust to suit.

---
Tags: audio, sound, music, sound-effects
---


# Question
Title: How can I find a bounding box for a bezier curve
I am using the code from the question Adding functionality to make individual anchor points of bezier continuous or non-continuous to create bezier curves (I added a line renderer).

How can I find the center of the curve for multiple cubic Bézier segments, where the centre of a bounding box is the centre of the curve (as in the image below)?

# Answer
You mentioned that you had a line renderer. If possible, the easiest way to find the bounds would be to track the min & max values for X & Y while rendering. If that's not possible, here's how to calculate the bounds after the fact.

The type of boundary box you're looking for is often called an axis aligned boundary box (AABB) because its sides are parallel (aligned) to the X & Y axis. This simplifies things because given multiple AABBs, we can an AABB that contains all the others by taking the min & max of their respective bounds. Thus, if we can find the AABB for each cubic Bézier segment, we can find the final answer.

Here's the overview of how to calculate an AABB for a cubic Bézier curve:

* Find the extremities (the x & y roots).
* Find all t values for roots.
* Discard any t values lower than 0 or higher than 1,because Bézier curves only use the interval \[0,1\].
* Track the lowest and highest results found when plugging the roots into the cubic Bézier equation: the lowest value is the lower bound, and the highest value is the upper bound for the bounding box we want to construct.

The derivative of a cubic curve is a quadratic curve, so we can find the roots Bézier curve means we can apply the quadratic formula. If `p1` is the start, `p2` is the first control point, `p3` is the second control point and `p4` is the end, we can solve for `t` as shown below. Note, because of the `±` there may be more than one value for t generated. $$\begin{align}t&={-b\pm\sqrt{b^2-4ac} \over 2a} \\ a &= 3(-p\_1+3p\_2-3p\_3+p\_4) \\ b &= 6(p\_1-2p\_2+p\_3) \\ c &= 3(p\_2-p\_1) \end{align} $$ Note that since your `p` values have both an X & Y component, you'll essentially run through the equations above twice: once for X & again for Y. Also, you will need to add some code that guards against division by zero.

Discard any `t` values that are less than 0 or greater than 1. Then take the remaining values, along with 0 & 1, and plug them into the formula for a cubic Bézier: $$f(t) = p\_1(1-t)^3 + 3p\_2t(1-t)^2 + 3p\_3t^2(1-t) + p\_4t^3$$

As you plug the `t` values in, check the results & save the smallest and largest X & Y values. Repeating the process for each curve will give you the min & max values for an AABB that encloses all of the curves examined.

To verify your answers during debugging, step through the cubic Bézier equation with some small value for `t`, for instance, `t = 0.001`. While this won't give you the exact roots, the results should be close enough to double check your work. You probably want to avoid this in your final code because it's not as accurate or efficient as solving for the roots.

Regarding your additional question on rotation: you can rotate the curve(s) around a point by rotating all of the start, end & control points around the point.

My main reference for this answer was Pomax's Primer on Bézier Curves, which I strongly recommend. You might also find this question on SO useful.
> 1 votes

---
Tags: unity
---


# Question
Title: Unity (UNET) Pass custom data when creating and joining a match in multiplayer
I've written some simple stuff to make a lobby for matchmaking. Now I want to pass some extra info besides the match name to the lobby. Something like Player's avatar and a number of players connected and what not. Thereto, I also want to pass information to the game from the players. For example, two players connect to a match and the character pick starts. For this I want to have the player's info regarding the characters they've picked and the character's weapons info (e.g. customized weapons info). I store all that in a json file and load from it to a class object. Is it ok to add these classes to, say, the player connection prefab that holds Network Identity or is it done somehow differently?

Can someone maybe help me with that in the context of Unity 2018 (i.e. give some advice or referrences to some relevant information)?

Appreciate all the help and thanks in advance.

# Answer
> 1 votes
you can send your information to other players inside lobby:

instead of sending avatar image , send avatar index

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

public class SendInformation : NetworkBehaviour {
    public class Soldier{
        public int avatarId{get;set;}
        public string playerName{get;set;}
        public bool isReady{get;set;}
    }
    public Soldier soldier;
    public Sprite[] Avatars;
    public Image image;

    void Start () {
        CmdSendData(0,"Jack",true);
    }

    [Command]
    void CmdSendData(int avatarId,string playerName,bool isReady){
    RpcSendData(avatarId,playerName,isReady);
    }

    [ClientRpc]
    void RpcSendData(int avatarId,string playerName,bool isReady){
        soldier.avatarId = avatarId;
        soldier.playerName = playerName;
        soldier.isReady = isReady;

        image = Avatars[soldier.avatarId];
    }
}

```

to get number of players connected use this:

```
var numOfConnectedPlayers = Network.connections.Length;

```

if you want to send json try this:

before using this script you should add `Newtonsoft.Json.dll` to your Plugins folder

```
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using Newtonsoft.Json;

public class JsonTest : NetworkBehaviour {

    public class Soldier{
    public string id {get;set;}
    public string Name {get;set;}
    public bool Level {get;set;}
    }
    public Soldier soldier;

    private void Start() {
    string jsonString = "{\"id\":1, \"Name\":\"Jack\", \"Level\":0}";
    CmdSendData(jsonString);
    }

    [Command]
    public void CmdSendData (string json) {
    RpcSendData(json);
    }

    [ClientRpc]
    public void RpcSendData (string json) {
        var information = JsonConvert.DeserializeObject<Soldier>(json);
        soldier.id = information.id;
        soldier.Level = information.Level;
        soldier.Name = information.Name;
    }
}

```

---
Tags: unity, multiplayer, matchmaking
---


# Question
Title: How can I let new players effectively compete with long-time players?
When new players join my strategy game, they have 3 days of protection from other players attacking them, but that's not enough time to catch up to players who have been playing for longer.

How can I solve this?

I thought of extending the protection time, but if I do that, players will not be able to progress without attacking (gaining more resources for faster progress).

The game is browser-based with a PHP back-end.

# Answer
The only similar system I know is OGame. In OGame, players are protected from other players until the have a certain amount of points (I think it is 50.000). It makes more sense to protect players based on their score instead of time, as score gives you a better aproximation on how powerful players are.

The theory is that with that many points, players are able to defend themselves at least at a basic level. But is not really points what provides protection to new players, but clans.

If you think about it, there is no way you can protect a newbie from the top players. That is why clans/guilds play a very important role in these kind of games. If you give players long enough time (a few days/weeks) they will be able to establish social links with other players and get a little bit better protected.

Another way to protect newbies is to organize the system in such a way that you are encouraged to only attack players with a similar power level to yours. In OGame, organizing an attack is a significant investment in time and resources. That is why a very strong player will never attack a newbie: the cost of the attack may be bigger than the benefit, or at least is not cost effective compared with attacking stronger players.
> 21 votes

# Answer
1. **Reduce progression** in your game mechanics. Avoid making players stronger in a game-mechanical sense based on how far they progressed in the game. That way an experienced player has no unfair advantage over an inexperienced player except for their game knowledge, which a new player can also acquire when they do their research.
2. **Herd your players**. When a player is new, put them against players which are also new, so that they have opponents of a similar level of progression and game knowledge. One way to do this is a league system where players can only attack players in the same league. Successful players are grouped together into higher leagues and unsuccessful players are moved down to leagues with weaker opponents. Should leagues be inappropriate for your game concept, for example because you have a shared open world, you could group players into world regions. Add an additional cost for attacking players which are far away geographically and put players into regions according to the date they started playing.
3. **Don't have negative consequences** for players getting attacked and losing. That way the veterans might farm the newbies for resources, but when the newbies do not have any disadvantage because of this, this is not a frustration factor. However, keep in mind that this means players have little reason to invest resources into defence.
> 10 votes

# Answer
The main problem you want to solve is strong, powerful players pick on weak, new players after their protection ends. There are quite a few social solutions to this:

* **Punish players for attacking those weaker than them:** The spoils of defeating another player should be decreasingly lower the more weak your opponent is (and they can be multiplied the stronger your opponent is compared to you) -- this is the solution Utopia uses.
* **Put players into groups that help each other.** Utopia puts all players in "islands" of up to 16 in a bunch. When someone attacks you, it can trigger retaliation from stronger players in your island.
* **Mentoring:** Give new users an in-game kick-back for actively mentoring new users. One web MMO I played lists new users to mentor and there's some process to follow to say "this person mentored me and I benefited"
> 4 votes

# Answer
Let's look at two examples of games that IMO do quite well to deter this behavior:

**Clash of Clans**: In Clash of Clans, new players are given a small amount of starting gold and elixir and a 3-day shield. This shield prevents other players from attacking the new player, but is removed if the new player attacks other players. This gives the new player 3 days to accumulate resources and upgrade buildings enough for a decent beginner-level defense.

* Progress can be measured roughly in two ways:
    + Town Hall level. The Town Hall limits what buildings are available to a player as well as what level the buildings can be upgraded to. A player must intentionally upgrade his/her Town Hall in order to progress to bigger and better bases.
    + Trophy count. Attacking someone else and winning gains you trophies. Losing causes you to lose trophies, though you won't lose nearly as many trophies as you would have gained by winning a round. Additionally, the player defending either gains or loses some trophies depending on how the battle went.

Now players are loosely separated by their Town Hall level as well as trophy count. The only thing that matches two players up is if the players have a similar trophy count. If someone with a level 2 Town Hall has 1000 trophies, then they will be matched up against other people with ~1000 trophies, regardless if their Town Hall is level 2 or level 10. This creates a soft barrier, as lower level players will run into a point where they cannot gain trophies past a certain point due to higher-level players primarily occupying that trophy bracket.

Additionally there is less benefit for higher level players attacking lower level players. The difference in Town Hall level determines how many resources a particular player can steal. If a level 5 player attacks a level 4 player, then they can only get 90% of the resources available. If they attack a level 3 player, that number drops to 50%. That means it becomes significantly less profitable to continue attacking players with a lower level to you due to the fact that you will end up spending more resources to attack for less resources in return.

**Runescape**: Yes, yes, we're talking about Runescape here. More specifically I'm going to be talking about oldschool Runescape due to the fact that last I played was somewhere in 2008 a little time after the wildy was removed and player trades sucked. More specifically, I'm going to focus on the wild and its mechanics instead of the non-combat areas.

In Runescape, player-vs-player combat is limited to an area called the Wild. This is an area that starts off at level 1, and progressively gets higher-levelled the deeper (further north) you get. This level determines the difference in combat levels that PvP is allowed. That means in level 1 Wild, a level 90 character could attack another character with a level between 89 and 91. Consequently a level 30 wild would allow much more varied combat scenarios.

* This is in part due to the nature of Combat Level. Combat Level is a cumulation of various individual stats on a character (Attack, Strength, Defense, Prayer, Ranged, Magic). Each stat maxes out at level 99, with combat level maxing out at 126. Someone who has level 99 ranged and the rest of the stats are level 1 is going to have a lower combat level than someone who has level 60 in attack/strength/defense, meaning this "Glass cannon" can go toe-to-toe with Mr. NothingSpecial.
* People lose gear when dying in the wild. Killing another player will allow you to pick up whatever gear they were wearing. If they haven't attacked anybody else, they still keep 3 items. If they have participated in PvP, then they keep nothing (unless they use a specific prayer). This creates an element of risk. Better gear means higher chance of survival, but a higher risk if you get killed.
* Consequently the added risk makes the Wild a good place to put good rewards in. For example, certain creatures are restricted to the wild that yield a high profit.

tl;dr: Depending on the exact nature of your game, either of these two ideas could give you a good sense of scale. Essentially you want it so that higher-level characters gain less by attacking lower-level characters, and gain more by attacking higher-level characters. Adding in some form of controlled risk allows players to progress at their own rate.
> 3 votes

# Answer
Different browser games I've played used different strategies for this. All came down to resetting all players on a set time.

One game dropped all new players in a new world with 400 at the same time, let them all compete against each-other until only one or a handful of alliances where remaining. A single round took about 1 month, and after that everybody could start a new game (new rounds started every few days).

Another one puts everybody in one pool (this used to be two pools, one for more advanced players, but when player base declined they reduced it to one). However, they reset the pool every X months (X=3 for them). When you join mid round, you stand no change to catch up to the top players, but after the reset, everybody has equal change and only skill makes the difference (and luck, cooperation etc). New players can use the round they join in to learn the ropes, and get a fresh and fair start after the reset.
> 2 votes

# Answer
Puzzle Pirates does this in a very direct, but effective way. In Puzzle Pirate, ships are ranked based on the rank of individual pirates manning the ship, and ships full of players weaker than you would appear with a blue might rings, while ships stronger than you would appear with red might rings.

If you attack too many blue ringed ships, then you'll be targeted by the Black Ship (El Pollo Diablo (The Devil Chicken)). The Black Ship is a super strong non playable ghost ship, filled with super strong non playable skellies. The ship is nigh invulnerable and undefeatable, with stats that normal ships can't even begin to dream to have. When you lose to the Black Ship, it will take away almost everything you have in your treasure booty, but you gain nothing if you somehow manage to defeat it instead.

This discourages people from getting into unfair fights.

Occasionally though, the black ship becomes a sport for really high ranking players. They try to get targeted by the black ship and try to defeat it for the just for the lulz (though those who dares doing this would usually target friendly ship that is set out for this particular purpose). Black ship hunting is unprofitable, so most players don't do that unless they're really bored. In the rare instances where someone managed to beat the ship, the game permanently upped the difficulty of the ship. Nowadays it's so ridiculously overpowered that you know your fate the moment it engages you.
> 1 votes

# Answer
There are multiple ways to deal with this:

1. Resetting the game: If you have a browser strategy game then the players that have been playing since the start will always have a resource advantage, resetting the game every few months will allow new players to join in.
2. If you have some sort of travel time rules you can place players that have a similar join time close to each other. Typically this means placing the players who joined first in the centre and the newer players outwards works quite well.
3. Limiting who you can attack to only allow attacks against players of a similar level.
4. Making defense more effective then offense. This means that players in general are less inclined to attack one another.
5. Allow players to construct something that prevents a constant number of resources from being stolen/lost upon being attacked. If I can prevent 100 of each resource from being stolen in an attack and I only have 100 resources then attacking me is not going to accomplish anything. A good player will likely skip this upgrade as they will quickly begin to dominate the local area. But a new player will be able to hide behind this building preventing him/her from being attacked.
6. Allow official alliances and let weak players give some sort of mechanical bonus towards being allied with a stronger player but make them lose a bit of this each time the weaker player is attacked. This should cause stronger players to protect their weaker allies. Maybe protectorate is a better name.
> 0 votes

# Answer
Hierarchies. Feudal structures.

Allow weak new players to swear allegiance to powerful established players. The overlord taxes his vassals some minor amount set by the overlord with a maximum tax rate set by the game admins; this tax rate is published to all players so that it can affect their decisions on whom to claim as overlord. This tax obligates the overlord to protect his vassals or lose their taxes. Perhaps the game mechanics force the overlord to come to the aide of his vassals, committing troops to the vassals defense. A rival could then use attacks on a rival overlords' vassals to try to weaken that overlord. The vassal commits some of his troops to assist his overlord when the vassal is offline in exchange for a lessening of the tax he normally pays. His troops gain experience for defending his overlord. All players can have an overlord and up to some maximum number of vassals set by the game admins. Perhaps the number of vassals permitted is directly related to how powerful the player is in relation to the total of all other players in the world. Circular rings of overlord-vassal would either be permitted or forced to be broken in certain situations by the game engine. When such a hierarchical structure has direct benefits for all players involved, both overlords and vassals have incentive to come to each others aide. When weak players have strong allies, the tendency to bully for resources gets punished fairly quickly, unless the bully learns to use strategy and his own allies to gain advantage in the game.

Combine this with other suggestions relating to the idea of diminishing returns for attacking much weaker players that was suggested by others and you have strategies that weak players can use to assist their more powerful allies.

Basically, you turn a war game where only the ruthless can gain and hold onto military power into a political game where those in power can get blindsided and stripped of power by their more politically adept opponents who use the masses of weaker players to their advantage.
> 0 votes

# Answer
Chess did a good job at making new players have an equal opportunity at winning. In that model the game scope was limited and not so verbose. In a complex rpg maybe you can allow lower lvl characters to take on characteristics of their opponents. This is very unrealistic but an approach to the "game balancing topic" in general which probably hasnt been approached much.

There was a defending the penguin game for wii that the enemies leveled and targeting systems seemed to cause the difficulty in balancing the game. Here the enemies were streamlined into battle. And the sheer number caused puzzles for players to solve.

In games like Ultima online I heard chickens could pwn everyone unlike in Zelda or less so in Fable.
> 0 votes

---
Tags: game-design, online, strategy, balance
---


# Question
Title: I need help in Unity OnTriggerEnter not changing my bool in an other script C#
I want to change a bool in 2 separate scripts in Unity but it's not changing `OnTriggerEnter` or stay or exit. I've tried everything but nothing helped me.

This is the script where I store the bool and the animator script:

```
public Animator _T1anim;
public bool Open;

void Awake()
{
    _T1anim = GetComponent<Animator>();
    _T1anim.SetBool("Open", false);
    _T1anim.SetBool("Close", true);
}
public void Update()
{
    if (Open != true)
    {
        CloseDoor();
    }
    else
        OpenDoor();
}
public void OpenDoor() {
        _T1anim.SetBool("Open", true);
        _T1anim.SetBool("Close", false);
}
public void CloseDoor()
{
    _T1anim.SetBool("Close", true);
    _T1anim.SetBool("Open", false);
}

```

and I want to change the "Open" Bool to true with the `OnTriggerEnter` in a different script. The `T1_1 T11` is the reference to the first script.

```
T1_1 T11;

void Awake()
{
    T11 = GetComponentInParent<T1_1>();
}
public void OnTriggerEneter(Collider other)
{

    if (other.tag == "Player")
    {
        T11.Open = true;
    }

}
}

```

This is the animator controller:

# Answer
> 1 votes
OnTriggerEnter is only called when one object' collider is set to Trigger and the other object also has a collider attached. Also one of the objects must have a rigidbody. See the Unity docs: https://docs.unity3d.com/ScriptReference/Collider.OnTriggerEnter.html

"Description

OnTriggerEnter is called when the Collider other enters the trigger.

This message is sent to the trigger Collider and the Rigidbody (if any) that the trigger Collider belongs to, and to the Rigidbody (or the Collider if there is no Rigidbody) that touches the trigger.

Notes: Trigger events are only sent if one of the Colliders also has a Rigidbody attached. Trigger events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions. OnTriggerEnter occurs on the FixedUpdate after a collision. The Colliders involved are not guaranteed to be at the point of initial contact."

Hope that this helps

# Answer
> -6 votes
Do you know what a boolean is its false or true but also could be 1 or 0 if you can set the bit by OR 1 or AND0 to clear

I think T1\_1 T11;set in other script make a local copy for that script not a global edit to the original variable.

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


# Question
Title: Fixing T-Junction artifacts in a BSP Editor
I'm starting a little BSP engine, and have begun implementing Brush CSG. Currently I represent my brushes as the enclosed volume of surface planes (like old idTech 3 maps), with a cache for each face that is generated on rendering the brush for the first time.

Now, I subtract a cube from another cube to cut a hole into it, yielding 5 brushes. Instantly, t-junctions! As you can see below, visible cracks appear:

This isn't particularly surprising, and obviously moving onto the BSP compilation process I will have to fix up all the t-junctions in the scene. However, I notice that in e.g. GtkRadiant, if I perform the same operation, these artifacts don't show up (or at least, I don't notice them), despite the fact the new brushes ARE separate and can even be moved apart and back together in the scene.

How do I remove this rendering issue at map design time?

# Answer
> 2 votes
The issue I experienced was NOT standard OpenGL behaviour.

I had accidentally enabled GL\_POLYGON\_OFFSET\_FILL in my code, which apparently causes the polygon fragments to not line up.

Disabling POLYGON\_OFFSET\_FILL fixed the problem.

---
Tags: opengl, rendering, binary-space-partitioning, csg
---


# Question
Title: Designing client-server to mitigate hosting advantage?
My game will be client-server, and I'd like to prevent the hosting player from enjoying the usual benefits you'd associate with playing on a server. For example, the advantage of the server running ahead of time compared to clients.

Are there simple ways of mitigating host advantage? Or do I have to make something complicated? My naive solution would be having the host run a "ghost" state, and a client state, on the same map.

The ghost state is an authoritative server simulation, it doesn't render the simulation which remains invisible, but does run ahead of time making calculations and decisions as usual. The host also plays a client on the same map, in which their input is regarded as any other client across the network, and like any other client is required to wait for the server simulation to make and transmit outputs. And so the host doesn't enjoy an advantage because they aren't playing the simulation which is making executive decisions on the game state ahead of client time.

Has this solution been done by any other games, or is there a better way of handling the problem?

# Answer
The best way to minimize host advantage is to have good lag compensation which makes sure that the outcomes match what the players see on their screens.

For example, When you are developing a first person shooter and want to know if a shot hits an opponent, take the latency of the shooter into account. If the shooter has a 40ms ping (round-trip time server-\>client-\>server), then check all hit collisions from the positions where the shooter was 20ms ago and against where the opponents were 40ms ago. That way you are detecting hits against what they saw on their screen when they pressed the fire button. When the victim's HP get reduced to zero that way, declare them dead but give them a grace period equal to their latency in which their shots are still counted (they made these shots before they saw their character die).

Yes, this might occasionally lead to implausible outcomes, like two high-pingers killing each other simultaneously with Hitscan weapons. But that's what you get with online gaming.

Lag compensation is a very wide topic, and the best practices and applicable techniques vary depending on the genre of your game. If you have any questions about how to mitigate lag advantage in a specific situation, feel free to post another question.
> 0 votes

---
Tags: networking, client-server
---


title: Canvas HTML5 Top View -> Isometric

text:
# Question
Title: Canvas HTML5 Top View -> Isometric
We are working in a simple MP strategy game using Node, Express and Sockets! I'm wondering if there's an easy approach to a transformation to make a Top View game into a 3D Isometric, without adding a Z axis to all positions in the game.

Ideally by just updating all the graphic files and the contents on drawing.js which is the controller in charge of doing all graphical operations.

```
function Drawing(context, images) {
  this.context = context;
  //this.context.imageSmoothingEnabled = false;
  this.images = images;
  console.log('once');
}

//show names
var show_names = '1';

/************************************************************/
/* Definiciones generales ***********************************/

Drawing.NAME_FONT             = '14px Questrial';
Drawing.NAME_COLOR            = '#FFF';
Drawing.HP_COLOR              = '#89D926';
Drawing.HP_MISSING_COLOR      = '#FF0000';
Drawing.SHIELD_COLOR          = '#26C6D9';
Drawing.SHIELD_MISSING_COLOR  = '#BEF8FF';
Drawing.BASE_IMG_URL          = '/public/img/';
Drawing.TILE_SIZE             = 2500;

/************************************************************/
/* Localizamos las imágenes a usar **************************/

Drawing.IMG_SRCS = {
  'explosion':              '/public/img/explosion.png',
  'smoke':                  '/public/img/smoke.svg',
  'panzer':                 '/public/img/panzer.png',
  'self_turret':            '/public/img/self_turret.png',
  'other_tank':             '/public/img/other_tank.png',
  'other_turret':           '/public/img/other_turret.png',
  'drone':                  '/public/img/drone.png',
  'shadow':                 '/public/img/broken_panzer.png',
  'nada':                   '/public/img/nada.png',
  'shield':                 '/public/img/shield.png',
  'ammo_regular':           '/public/img/game/ammo/regular.png',
  'ammo_healco_care':       '/public/img/game/ammo/healco_care.png',
  'ammo_slowco_frozen':     '/public/img/game/ammo/slowco_frozen.png',
  'tile':                   '/public/img/full_map_02.png',
  'shotgun_powerup':        '/public/img/shotgun_powerup.png',
  'speedboost_powerup':     '/public/img/speedboost_powerup.png',
  'rapidfire_powerup':      '/public/img/rapidfire_powerup.png',
  'shield_powerup':         '/public/img/shield_powerup.png',
  'healthpack_powerup':     '/public/img/healthpack_powerup.png',
  'explosion_media':        '/public/img/explosion.png',
  'zombie':                 '/public/img/boxes.png',
  'people':                 '/public/img/boxes.png',
};

/************************************************************/
/* Crea las imagenes en canvas ******************************/

Drawing.create = function(context) {
  var images = {};
  for (var key in Drawing.IMG_SRCS) {
    images[key] = new Image();
    images[key].src = Drawing.IMG_SRCS[key];
  }
  return new Drawing(context, images);
};

/************************************************************/
/* Limpiamos el canvas **************************************/

Drawing.prototype.clear = function() {
  this.context.clearRect(0, 0, Constants.CANVAS_WIDTH, Constants.CANVAS_HEIGHT);
};

/************************************************************/
/* Crea las unidades en el mapa *****************************/

Drawing.prototype.drawTank = function(isSelf, coords, orientation, turretAngle, name, kind, health, hasShield, shieldsize) {
  if (show_names == 1) {
    this.context.save();
    //presición pixelar
    coords[0] = (0.5 + coords[0]) | 0;
    coords[1] = (0.5 + coords[1]) | 0;
    //ahora si
    this.context.translate(coords[0], coords[1]);
    this.context.textAlign = 'center';
    this.context.font = Drawing.NAME_FONT;
    this.context.fillStyle = Drawing.NAME_COLOR;
    this.context.fillText(name, 0, -50);
    this.context.restore();
    this.context.save();
    //presición pixelar
    coords[0] = (0.5 + coords[0]) | 0;
    coords[1] = (0.5 + coords[1]) | 0;
    //ahora si
    this.context.translate(coords[0], coords[1]);
    //los pixeles que ocupa cada unidad
    var unidad_w = 3;
    //barra de escude
    if (hasShield != null && hasShield != undefined) {
      //console.log('shield size: ' + shieldsize);
      for (var s = 0; s < 20; s++) {
        //escude
        if (s < shieldsize) {
          this.context.fillStyle = Drawing.SHIELD_COLOR;
          this.context.fillRect((s * unidad_w) + (unidad_w * 10), -42, unidad_w, 5);
        }
      }
    }
    //barra de vida
    for (var i = 0; i < 20; i++) {
      //salud
      if (i < health) {
        this.context.fillStyle = Drawing.HP_COLOR;
        this.context.fillRect((i * unidad_w) - (unidad_w * 10), -42, unidad_w, 5);
      }
      //salud perdida
      else {
        this.context.fillStyle = Drawing.HP_MISSING_COLOR;
        this.context.fillRect((i * unidad_w) - (unidad_w * 10), -42, unidad_w, 5);
        }
    }
    //c-c-coom-bo breaker!
    this.context.restore();
  }
  this.context.save();
  //presición pixelar
  coords[0] = (0.5 + coords[0]) | 0;
  coords[1] = (0.5 + coords[1]) | 0;
  //ahora si
  this.context.translate(coords[0], coords[1]);
  this.context.rotate(orientation);
  //acá arma la unidad
  var unidad = null;
  if (kind == "drone") { unidad = this.images['drone']; }
  if (kind == "panzer") { unidad = this.images['panzer']; }
  if (kind == "shadow") { unidad = this.images['shadow']; }
  //draw, primero el normal, después el volado
  if (kind != "shadow") { this.context.drawImage(unidad, -unidad.width / 2, -unidad.height / 2); }
  if (kind == "shadow") { this.context.drawImage(unidad, -170, -128); }
  //acomodamos
  this.context.restore();
  this.context.save();
  //presición pixelar
  coords[0] = (0.5 + coords[0]) | 0;
  coords[1] = (0.5 + coords[1]) | 0;
  //ahora si
  this.context.translate(coords[0], coords[1]);
  this.context.rotate(turretAngle);
  //acá arma el cañon
  var turret = null;
  if (kind == "drone") { turret = this.images['nada']; }
  if (kind == "panzer") { turret = this.images['self_turret']; }
  if (kind == "shadow") { turret = this.images['nada']; }
  this.context.drawImage(turret, -turret.width / 2, -turret.height / 2);
  this.context.restore();
  //revisa si posee escudo
  if (hasShield != null && hasShield != undefined) {
  this.context.save();
  //presición pixelar
  coords[0] = (0.5 + coords[0]) | 0;
  coords[1] = (0.5 + coords[1]) | 0;
  //ahora si
  this.context.translate(coords[0], coords[1]);
  var shield = this.images['shield'];
  this.context.drawImage(shield, -shield.width / 2, -shield.height / 2);
  this.context.restore();
  }
  //usando las proximas 7 lineas es posible hacer que la unidad disipe fuego.
  if (health < 3) {
  this.context.save();
  //presición pixelar
  coords[0] = (0.5 + coords[0]) | 0;
  coords[1] = (0.5 + coords[1]) | 0;
  //ahora si
  this.context.translate(coords[0], coords[1]);
  var smoke = this.images['smoke'];
  this.context.drawImage(smoke, -smoke.width / 2, -smoke.height / 2);
  this.context.restore();
  }

};

/************************************************************/
/* Creación de balas ****************************************/

Drawing.prototype.drawBullet = function(coords, orientation, ammo, source_x, source_y) {
  this.context.save();
  //presición pixelar
  coords[0] = (0.5 + coords[0]) | 0;
  coords[1] = (0.5 + coords[1]) | 0;

  //pixel wise, hace rendir más el GPU, previniendo posiciones imposibles
  source_x = (0.5 + source_x) | 0;
  source_y = (0.5 + source_y) | 0;

  //lineas
  this.context.beginPath();
  this.context.moveTo(source_x, source_y);
  this.context.lineTo(coords[0], coords[1]);

  //disfuminación de linea
  var grad = this.context.createLinearGradient(source_x, source_y, coords[0], coords[1]);
  grad.addColorStop(0, 'transparent');

  //color de la linea
  if(ammo == 'slowco_frozen') { grad.addColorStop(1, '#0B95FB'); }
  else if(ammo == 'healco_care') { grad.addColorStop(1, '#6CFA0B'); }
  else { grad.addColorStop(1, '#FF3939'); }
  this.context.strokeStyle = grad;
  this.context.stroke();

  //ahora si, la imagen
  this.context.translate(coords[0], coords[1]);
  this.context.rotate(orientation);
  var bullet = this.images['ammo_regular'];
  if(ammo == 'slowco_frozen') { var bullet = this.images['ammo_slowco_frozen']; }
  if(ammo == 'healco_care') { var bullet = this.images['ammo_healco_care']; }
  this.context.drawImage(bullet, -bullet.width / 2, -bullet.height / 2);
  //this.context.filter = 'blur(3px)';
  //this.context.drawImage(bullet, -bullet.width / 2, -bullet.height / 2);
  this.context.restore();
};

/************************************************************/
/* Creación de bloques **************************************/

Drawing.prototype.drawBlock = function(coords, name) {
  this.context.save();
  //presición pixelar
  coords[0] = (0.5 + coords[0]) | 0;
  coords[1] = (0.5 + coords[1]) | 0;
  //ahora si
  this.context.translate(coords[0], coords[1]);
  var block_media = this.images[name];
  this.context.drawImage(block_media, -block_media.width / 2, -block_media.height / 2);
  this.context.restore();
};

/************************************************************/
/* Creación de powerups *************************************/

Drawing.prototype.drawPowerup = function(coords, name) {
  this.context.save();
  //presición pixelar
  coords[0] = (0.5 + coords[0]) | 0;
  coords[1] = (0.5 + coords[1]) | 0;
  //ahora si
  this.context.translate(coords[0], coords[1]);
  var powerup_icon = this.images[name];
  this.context.drawImage(powerup_icon, -powerup_icon.width / 2, -powerup_icon.height / 2);
  this.context.restore();
};

/************************************************************/
/* Creación de explosiones **********************************/

Drawing.prototype.drawExplosion = function(coords) {
  this.context.save();
  //presición pixelar
  coords[0] = (0.5 + coords[0]) | 0;
  coords[1] = (0.5 + coords[1]) | 0;
  //ahora si
  this.context.translate(coords[0], coords[1]);
  var explosion_media = this.images['explosion_media'];
  this.context.drawImage(explosion_media, -explosion_media.width / 2, -explosion_media.height / 2);
  this.context.restore();
};

/************************************************************/
/* Creación del mapa ****************************************/

 // param {number} minX The minimum canvas x coordinate to start drawing from.
 // param {number} minY The minimum canvas y coordinate to start drawing from.
 // param {number} maxX The maximum canvas x coordinate to draw to.
 // param {number} maxY The maximum canvas y coordinate to draw to.

Drawing.prototype.drawTiles = function(minX, minY, maxX, maxY, salud) {
  this.context.save();
  var tile = this.images['tile'];
  for (var x = minX; x < maxX; x += Drawing.TILE_SIZE) {
    for (var y = minY; y < maxY; y += Drawing.TILE_SIZE) {
      this.context.drawImage(tile, x, y);
    }
  }
  this.context.restore();
};
```

My apologies if this question isn't good, first one here I believe!

Thanks in advance! Chris

# Answer
> -1 votes
Well Chris, I am not going to pretend that I know how to do this from scratch. And that's isn't because I don't want to, but mainly because there are a good number of better options out there.

For example, if you were using PhaserJS you could add a plugin that converts your game from flat 2D to an isometric view.

---
Tags: javascript, html-canvas, isometric, node.js
---


# Question
Title: Ignore collisions with some objects in certain contexts
I'm making a racing game with cars in Unity. The car has a boost/nitro powerup. While boosting, I wouldn't want to be deviated when colliding with zombies, but I do want to be deviated when colliding with walls.

On the other hand, I don't want to ignore collision with zombies, because I still want to hit them on impact.

How should I handle this? Basically, what I want is for the car to not rotate when colliding with certain objects.

# Answer
> 7 votes
# Consider manipulating your layers at runtime.

## Enabling/disabling collisions for certain objects with entire layers

Physics.IgnoreCollision and Physics.IgnoreLayerCollision allow you to disable collisions between two colliders, and between two layers, respectively.

If you want to exclude a specific collider from collisions, there's no built in way to do that. If you are using non-kinematic rigidbodies with non-trigger colliders, there will always be a response even if you try to filter out the responses by tag.

The way we accomplished this on our project was to create a layer named "Void". Void does not collide with anything at all.

Now you can temporarily disable a collider's collision by setting its layer to "Void", and re-enable it by restoring its old layer.

Here's the gist:

```
int oldLayer = -1;
int voidLayer;

void Start()
{
    voidLayer = LayerMask.NameToLayer("Void");
}

void DisableCollider(Collider col)
{
    oldLayer = col.gameObject.layer;
    col.gameObject.layer = voidLayer;
}

void EnableCollider(Collider col)
{
    col.gameObject.layer = oldLayer;
}

```

We did this specifically because enabling and disabling colliders that were children of rigidbodies can really screw things up in some circumstances. So you can't reliably disable part of a compound rigidbody collider, but you can reliably swap around the layer of one of the compound collider parts.

## Now your specific situation

To reduce the impact zombie collision has on your car, consider making your zombies kinematic rigidbody triggers, or otherwise making their mass very very small (like float.Epsilon), so the impact has zero effect on the car's momentum. On impact, you can also do this layer switch, so that subsequent collisions aren't triggered, even if the first one applies a negligible force to the car body.

You could even switch them to a layer that just doesn't collide with the car.

You could also put another collider on zombies that get activated on ran-over. This way you can fake impact forces OnTriggerEnter. You can't get as accurate with it, but you can approximate where the contact normals may have been well enough to throw the zombie somewhere fun.

You have to ask yourself:

* Do I want to be able to knock the ran-over zombies around with my car, or should they just play a death animation?
* Do I care if the car's velocity and angular velocity are affected in smaller ways by hitting zombies?

# Answer
> 1 votes
Call Physics.IgnoreCollision on all the zombies, passing the function the player object as well, when the car starts boosting. This will cause Unity to not react to any collisions between the player and the zombies. When the car is finished boosting, call `Physics.IgnoreCollision` again for each zombie, passing it the player object and `false` to cause collision-response to start again.

# Answer
> 0 votes
I'm guessing you can check the names of the objects, or add a name value to the objects classes then check that?

```
bool boosting = false; //need a trigger in the game to set this to true.

function OnCollisionEnter(theCollision : Collision)
{
    if (boosting == true)
    {
        if(theCollision.gameObject.name == "Zombie")
        {
              Debug.Log("Zombie hit during boost");
        }
        else if(theCollision.gameObject.name == "Wall")
        {
              Debug.Log("Wall hit during boost");
        }
    }
    else
    {
        if(theCollision.gameObject.name == "Zombie")
        {
              Debug.Log("Zombie hit not in boost");
        }
        else if(theCollision.gameObject.name == "Wall")
        {
              Debug.Log("Wall hit not in boost");
        }
    }
}

```

Then just have another variable you can use to check for boosting and add that to the checks.

EDIT: added this variable in.

# Answer
> 0 votes
I assume you are using the physics engine to do the 'deviation' automatically based on shape/mass when things collide together? if that is the case, then change the mass of your zombies to a very minimal value and they won't affect the car.

# Answer
> 0 votes
There are two classes of answers here:

1. Ignoring or disabling collisions
    * These solutions will not solve the problem, he wants the zombies to go flying when hit.
2. Changing mass:
    * This is a good approach. Don't forget to also change Inertia accordingly.
        + You could alternatively change the cars Mass and Inertia when boosting (we do this to reduce the impact of all non-kinematic objects on a car when boosting)
        + This should not effect the road or walls assuming that those are kinematic.

Hope this helps!

---
Tags: collision-detection, unity
---


# Question
Title: Object made of cubes looks different based on the distance in Unity3D?
I made a ***"Wall"*** from basic Unity3D cubes. They are placed **tightly** so the wall looks like **one big rectangular prism**.

If I look at it from **close distance**, it looks as it should be: **one big rectangular prism**.

But if I start **moving backwards, away from the wall**, the **cubes' edges become visible**:

And this whole thing happens in a **circular way**.

* If I just start moving backwards from the wall,
* first I start to see the cubes' edges just at the further parts of the object, and then the **pure white** circle starts shrinking, the edges become visible at bigger and bigger parts of the object.
* then the **blurrier** edges appear at the further places and the previously appeared **sharper** edges circle starts shrinking as well. **(this phase is shown on the image above)**

This should be some kind of shading optimization, like mipmap, right?

How can I fix this? **I want the wall to be seamless from all distances.**

**Update:**

* Changing the shader to `Unlit > Color`, **fixes the issue.**
* This thing only occurs on the **lit side** of the wall. The shadowy side of the wall, *(which isn't lit directly by the directional light of the scene)* is rendered normally.

# Answer
Finally I managed to fix it, with the help of the **official Unity Forums**. (*20 minutes after posting, there was already an answer)*

**I just had to increase the (Shadow) Bias of my light source.**

*(Increasing it from 0.05 to 0.3 fully removed all the edges.)*
> 2 votes

---
Tags: unity, graphics, shading
---


# Question
Title: How to change two rotation axes in Unity without affecting the third?
I have a GameObject in Unity and I need to change its X and Z rotation without doing anything with the Y, as that would mess up everything.
Note that this sets the Y rotation to 0 and I don't want that (I want it to let it be be what it already is), so this isn't any good:

```
gameObject.transform.rotation = Quaternion.Euler(someNewAngle, 0f, someNewAngle);

```

What should I do?

# Answer
Just take the previous value of the Y rotation using `transform.rotation.eulerAngles`.

So your code would look like this:

```
var yRotation = gameObject.transform.rotation.eulerAngles.y;
gameObject.transform.rotation = Quaternion.Euler(someNewAngle, yRotation, someNewAngle);

```
> 1 votes

---
Tags: unity, rotation, euler-angles
---


# Question
Title: What are the best alternatives to Unity Asset Store for publishing game assets?
I'm not sure if this is the right place to ask this so go easy on down-voting

# Answer
Check out these sites:

1. https://itch.io
2. https://www.gamedevmarket.net
3. https://craftpix.net

gamedevmarket allows you to sell your assets but I'm not sure of the rest, just check them out, I'm pretty sure they will help
> 1 votes

---
Tags: assets, publishing
---


# Question
Title: How to rotate a whole Bezier Curve around a given point
I am using the code from the question Adding functionality to make individual anchor points of bezier continuous or non-continuous to create bezier curves (I added a line renderer).

How can I rotate the whole bezier curve (which may contain multiple cubic Bézier segments) around a point?

Please note that the rotation point could be any point including the one of the curves anchor points or control points.

# Answer
> 4 votes
Any affine transformation of a Bezier curve can be accomplished by applying that affine transformation to its anchor & control points.

This extends to Bezier splines, consisting of multiple Bezier curve segments.

So, to rotate a spline by the rotation R, simply rotate each anchor & control point by R.

Keep in mind that if you store your control points as offsets from the anchor points, rather than as explicit positions on their own, you'll need to transform them as offset vectors instead of as points (ie. if using a homogeneous matrix, the final component of the vector should be 0 instead of 1 so that it ignores translation)

---
Tags: unity
---


# Question
Title: As a client, trying to get a coder/programmer to develop my ideas into a functioning program, what should I be providing to my developer(s)?
I am the director of a start-up game development group (I say "group" because it is not yet an official company). I have recently gained the willingness of a few coders who are willing to help me with the project, but they are asking for documentation.

I understand the need for documentation, and I have a lot of our ideas in a few different documents, but I imagine that I will want to organize it in some way that the developers can understand individually as well as collectively.

Is there anything I should leave out of such a document; if so, what kind of things? Is there an appropriate template for this kind of document; if yes, where can I find it? Is there anything else that I should know to offer the coders before they begin their work?

I know that I have many questions being asked here. I hope that isn't a problem. Thank you in advance for any guidance!

# Answer
> 46 votes
Game development usually works a bit different than application development. The reason is that games usually have far fewer and far less stringent requirements. You don't have a well-defined business problem your software is supposed to solve. The only true requirements of a game are "runs properly on the target platform", "appeals to the target demographic" and "is fun to play" (and maybe "sells a lot of microtransactions" if you are in that section of the industry). Everything else is subject to change during the development.

However, in order to make sure that all developers of the game are working in the same direction and not end up fighting to the death over creative differences, you should have some codified "vision" of how you want the final game to look and play. This vision is usually codified in a Game Design Document. Such a document usually describes:

* The basic premise of the game:
    + The elevator pitch: The main game idea, described as briefly as possible.
    + What is the genre of the game?
    + Who is your target demographic?
    + Which platform(s) are you targeting?
* The game mechanics:
    + What actions can the player perform in this game and how do they affect the game?
    + What non-player entities are in the game, how do they behave, and how do they interact with each other and with the player?
* The scope:
    + How much content do you want the game to have?
    + What level of quality do you want that content to have?
* The aesthetic direction of the game:
    + What general atmosphere do you want the game to have?
    + How do you want the game to look?
    + How do you want the game to sound?
* When it comes to story, it depends a lot on the genre. Some games need no story at all. Many games only need a few sentences. But if you are creating a plot-driven game, like an RPG or adventure, then this can be in fact the longest part of the design document and can include:
    + A description of the world in which the game takes place and its key locations
    + A description of the important characters, their looks, their personality and their backstory
    + A basic outline of the plot which is told during the game

If you look around the web, you can find a lot of templates for game design documents. The game industry is a lot less into formalities and standardized processes than the rest of the industry, so you won't find the one ISO-standard to rule them all. Just try to find one style which fits your project, your team and your work methodology.

However, be open to changes during development. When game design documents of popular games leak to the public, either intentionally or unintentionally, you can usually notice something interesting. If you compare these early design notes to the finished game, there will usually be lots of considerable differences. This is usually the result of a design process game developers call Fail Faster:

1. Come up with a rough design
2. Create a simple prototype
3. Playtest it with a critical mindset and figure out what does not work about it
4. Revise your design
5. Go back to stage 2

So do not be afraid to change or cut features when you realize during playtesting that they aren't actually as fun as they were in your head. Also, be open to suggestions from the team. Most people in the game development industry decided to join the industry because they want to put their own game ideas into practice. So giving your team some creative influence can be a great motivator for them. But as a good producer, it is also your duty to say "No!" if you think an idea wouldn't work or would exceed the budget.

I am looking forward to playing your game.

---
Tags: documentation, design-document, outsourcing
---


# Question
Title: What would be the optimal order to render something with OpenGL
That question mind sound dumb, but let me explain: I'm writing a 3D rendering engine in C++, and my way of getting something to the screen seems rather unintuitive:

I really hope that my artwork is understandable. To be sure, I'll just explain it again with words.

1. **\[class Mesh\]** Load a raw mesh with vertices, uv coordinates, normals, etc
2. **\[class Model\]** Creates VBO's off the data from the Mesh
3. **\[class Shader\]** Reads and compiles shader
4. **\[class RenderObject\]** Binds Shader
5. **\[class RenderObject\]** Sets uniforms
6. **\[class RenderObject\]** Binds Model VBO
7. **\[class RenderObject\]** draw call

That would be how I get something drawn on the screen. Is that the proper way of doing so? Is there a more or less standard way of doing this?

# Answer
> Is there a more or less standard way of doing this?

Yes, there is; I would honestly say that it depends on your game:

If you are making a simple 2D game, with maximum 20/40 sprites at the time being rendered onto the screen, that ^ is an acceptable method, even if not the fastest.

If you are planning to port your game to mobile for example, you *definitely* need a faster way of rendering things on the screen.

For that, I would suggest you to take a look at *Data Batching*.

As the name already states, Data Batching is a process where you load all the data you want to render inside a single buffer (a *Batch*) and pass that to a `Renderer` of some sort, which then sends everything to the GPU and makes the draw call / draw calls (In OpenGL for example, you would call `glMapBuffer(...)`, set the data, and call `glUnmapBuffer()`).

This way, instead of having a **1 object to 1 draw call** ratio (which is quite expensive), you would have a **x objects to 1 or 2 drawcalls** ratio (depending on how you want to handle the buffer).
> 1 votes

# Answer
This is the bare bone structure and that's how a simple object is rendered. These are the things which you have to do,the optimization lies in the fact that how many times you bind or unbind an entity.

You should use which ever layout you want but it should keep the binding calls to its minimum.

eg- setting the uniform while you bind program while creating it minght reduce some program binding statements.

off course sometime it cant be avoided, so the best way is to try and keep less binding calls and be done with one entity in its first bind.
> 0 votes

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


# Question
Title: How to implement a camera for a TiledMap with SDL2 and Box2d?
I m writing a game engine using mainly SDL2 and box2D, I implemented TiledMap class that loads a tmx map and everything is fine it even support animation and objects that later will generate Box2D bodies for collision

Everything is fine till Camera came in I implemented camera class and its working fine for the sprites and the map but something is annoying me the bodies that get generated will stay at their position when the camera moves!

To illustrate the problem see these screenshots:

Without moving the camera the result is normal:

I tried to come up with some solution one of them is to translate all of the map bodies backward. The solution honestly worked but have some side effects that made me not satisfied at all with the result

* Expensive (specially if your setting the camera every frame)
* Results in a non physical behavior !

Finally I will show some code so the reader will understand exactly what Im doing:

Camera Class:

```
void Camera::addObjectToCamera(TiledMap* map)
{
    m_CameraAttachedObjects.emplace_back(map);
}

void Camera::moveCamera(Vec2i p_Offset)
{
    m_CamPos += p_Offset;
    for (auto& obj : m_CameraAttachedObjects)
    {
        p_Offset.x = -p_Offset.x;
        obj->translateMap(p_Offset);
    }
}

void Camera::setCameraPosition(Vec2i p_Pos)
{
    m_CamPos = p_Pos;
    for (auto& obj : m_CameraAttachedObjects)
    {
        obj->setPosition(p_Pos);
    }
}

```

TiledMap class:

```
void TiledMap::render(float dt)
{
    SDL_RenderCopy(r, m_MapTexture, &m_MapSrc, NULL);
}

void TiledMap::setPosition(Vec2i pos)
{
    static Vec2i LastPositionTranslated = Vec2i(0, 0);
    if (Utility::IsInBox(Vec2i(pos.x, pos.y), Vec2i(0,0), Vec2i(m_MapDst.w, m_MapDst.h))) {
        m_Position = pos;
        m_MapSrc.x = pos.x;
        m_MapSrc.y = pos.y;
        for (auto& itr : m_cachedAnimatiedTiles) {
            auto current_rect = itr->tiledLayerData->DestDraw;
            itr->tiledLayerData->DestDraw->x = current_rect->x - (pos.x - LastPositionTranslated.x);
            itr->tiledLayerData->DestDraw->y = current_rect->y - (pos.y - LastPositionTranslated.y);
        }
        for (auto& phyObj : m_allMapBodies) {
            Vec2f old_transform = phyObj->GetTransform().p;
            phyObj->SetTransform
            (
                Vec2f(old_transform.x-float(pos.x - LastPositionTranslated.x), old_transform.y-float(pos.y - LastPositionTranslated.y))
                ,0.f
            );
        }
        LastPositionTranslated = pos;
    }
}

void TiledMap::translateMap(Vec2i pos)
{
    if (Utility::IsInBox(Vec2i(m_MapSrc.x - pos.x, m_MapSrc.y - pos.y), Vec2i(0, 0), Vec2i(m_MapDst.w, m_MapDst.h))) {
        m_Position += pos;
        m_MapSrc.x -= pos.x;
        m_MapSrc.y -= pos.y;
        for (auto& itr : m_cachedAnimatiedTiles) {
            auto current_rect = itr->tiledLayerData->DestDraw;
            itr->tiledLayerData->DestDraw->x = current_rect->x + pos.x;
            itr->tiledLayerData->DestDraw->y = current_rect->y + pos.y;
        }
        for (auto& phyObj : m_allMapBodies) {
            Vec2f old_transform = phyObj->GetTransform().p;
            phyObj->SetTransform(old_transform + Vec2f((float)(pos.x), (float)(pos.y)), 0.f);
        }
    }
}

```

Game class (game manager):

```
            body->SetLinearVelocity(Vec2f(20.f, body->GetLinearVelocity().y));
        cam->moveCamera(Vec2i(10, 0));

```

the current code is translating the bodies too which is i consider a bad solution of my initial problem anyone have better solution to scroll in box2d? (See another part of the box2d world)

I aiming later (after fixing this problem) to position the camera to follow my player.

**Note**: I know my camera is kinda fake and its just change which part of the map texture to draw but there is no other way to do it .

# Answer
> 1 votes
Looking at your code, it looks like your camera actually moves the physics objects in the world. This is not a common approach. It's hard to judge what you do with the visual objects, but it seems like you only move the position where they are rendered, and not their logical world position, is that correct?

In any case, the pattern I use when creating cameras, is keeping the camera offset in the camera, and only applying it to the sprite objects when rendering the level. This way the world simulation keeps running just fine, and the rendering code is also nicely decoupled from the movement code.

So, you would move your camera just like you currently are, but don't apply the offset to the objects in your world. Instead, in your rendering function for the level, do something like the following:

```
void Level::Render()
{
    auto cameraOffset = m_Camera->GetOffset();

    for (auto& object : m_Objects)
    {
        Sprite* sprite = object->GetSprite();
        sprite->SetPosition(object->GetWorldPosition() + cameraOffset);

        Renderer::RenderSprite(sprite);
    }

    if (Globals::DoDebugRendering)
    {
        for (auto& geometry : m_Geometry)
        {
            Renderer:RenderShapeAt(geometry, geometry->GetOrigin() + cameraOffset);
        }
    }
}

```

So just to clarify, the goal is to keep the position changes caused by the camera totally visual, and unrelated to the objects' positions in the game world.

---
Tags: c++, box2d, sdl2
---


# Question
Title: Why doesn't SDL2 recognize a game controller button press?
SDL2 recognizes my PS4 controller but not the button presses. Here is a minimal code example.

```
#include <SDL2/SDL.h>
#include <stdio.h>

int main(int argc, char** argv) {
  if (SDL_Init(SDL_INIT_VIDEO) != 0 ) {
    printf("Unable to initialize SDL (%s)\n",SDL_GetError());
    printf("Exit\n");
    return -1;
  }

  SDL_InitSubSystem(SDL_INIT_GAMECONTROLLER);

  SDL_GameController *gameController = NULL;
  int numJoysticks;
  numJoysticks = SDL_NumJoysticks();
  printf("%d joysticks found\n", numJoysticks);

  if( numJoysticks <= 0 ) {
    return -1;
  }

  if( ! SDL_IsGameController(0) ) {
    printf("Error: joystick 0 is not a game controller\n");
    printf("Exit\n");
    SDL_Quit();
    return -1;
  }

  gameController = SDL_GameControllerOpen(0);

  if( ! gameController ) {
    printf("No game controller found\n");
    printf("Exit\n");
    SDL_Quit();
  }

  printf("Opened Game Controller 0\n");
  printf("Found a valid controller, named: %s\n", SDL_GameControllerName(gameController));

  if( SDL_GameControllerGetButton(gameController, SDL_CONTROLLER_BUTTON_A) ) {
    printf("Button press!\n"); // Never printed
  }

  // Exit
  SDL_GameControllerClose(gameController);
  SDL_Quit();
  return 0;
}

```

Here is the output I get:

```
1 joysticks found
Opened Game Controller 0
Found a valid controller, named: PS4 Controller

```

What am I doing wrong?

# Answer
You are only polling the button press once, at a very specific moment. It's very likely that the button is not pressed at that time, and you miss the event. Try replacing the `if( SDL_GameControllerGetButton(gameController, SDL_CONTROLLER_BUTTON_A) )` statement with the following:

```
bool poll = true;

while (poll)
{
    SDL_Event e;
    while (SDL_PollEvent(&e))
    {
        if (e.type == SDL_CONTROLLERBUTTONDOWN && e.cbutton.button == SDL_CONTROLLER_BUTTON_A)
        {
            printf("Button press!\n");
            poll = false;
            break;
        }
    }
}

```

The code runs a loop that polls the button state until you press it down, and then stops.
> 2 votes

---
Tags: sdl2
---


title: Why some textures become black in GDX

text:
# Question
Title: Why some textures become black in GDX
I have such situation in my GDX game: I have a static class that manage my `Drawables`. It's a Singleton. I want to load all my `Textures` to it in order not to load them at every turn when I switch between screens (I know this is bad practice but I need this). I pack my resources into a TextureAtlas and load them. But when I pack and load more then some amount of `Textures` and try to use them some of them become black. Why this is happens? How can I bypass this unfortunate case. The size of my TextureAtlas (four images and one .txt file) is about 4MB.

# Answer
> 0 votes
Well. I hope this will help somebody. Some of my textures were black because of their resolution. The resolution of one of them was something about 1200x2400 pixels. If you have similar problem, try to juts decrease resolution of textures.

# Answer
> 1 votes
https://github.com/mattdesl/lwjgl-basics/wiki/LibGDX-Textures

Read this and especially **Hardware Limitations** part. Each phone/pc has it's max\_texture\_size and if exceeded - will print a black texture.

# Answer
> 0 votes
If you have bad texture coordinates this can happen. But it could be your texture atlas itself is wrong or you even try to use the wrong atlas. So check that as well.

# Answer
> 0 votes
I was also getting a black square when trying to draw some of the textures on IOS. It turns out the problem was that I was using MipMap and the image sizes were not a power of 2.

```
texture.setFilter(Texture.TextureFilter.MipMap, Texture.TextureFilter.Nearest);

```

See: https://github.com/libgdx/libgdx/issues/1296

OpenGL ES 2.0 support non-power-of-two images, but not for everything. Specifically, it does not require support for repeat or mipmap with non-power-of-two textures. If you require those features, you should use power-of-two images

---
Tags: opengl, libgdx, textures, assets, texture-atlas
---


# Question
Title: NullReferenceException in my inventory system
I'm making a simplified inventory system for a 3d game.

When I try to pick up an object, I get the following error:

> NullReferenceException: Object reference not set to an instance of an object

Here are the scripts I'm using:

**Pick Up** goes on the item - the error fires inside the Update method

```
public class PickUp : MonoBehaviour {
    private playerInventory inventory;
    public Transform woodIcon;
    public Transform slot1;
    public void Start()
    {
        inventory = GameObject.FindGameObjectWithTag("Player").GetComponent<playerInventory>();
    }

    public void Update()
    {
        if (inventory.slot1 == true) // <-- error fires on this line.
        {
            Destroy(gameObject);
            Instantiate(woodIcon, slot1.position, woodIcon.rotation);
        }
    }
}

```

**Player Inventory**

```
public class playerInventory : MonoBehaviour {

    public bool slot1;

    public void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.name == "wood")
        {

        }
        if (slot1 == false)
        {
            slot1 = true;
        }
    }
}

```

Here is a screen shot showing my setup and the error:

# Answer
You are trying to find the game object with the inventory with `GameObject.FindGameObjectWithTag("Player")`. However, the game object with the player inventory which you show on the screenshot has the Tag "Untagged".

That means `FindGameObjectWithTag` returns `null`. You then try to call `.GetComponent` on a `null` object, which throws the first `NullReferenceException` and crashes your `Start` method. The variable `private playerInventory inventory;` stays `null`, so you get further exceptions whenever you try to access `inventory.slot1`.

In order to fix this problem, change the tag of the player game object to "Player".

There also seems to be something which isn't *syntactically* but *logically* weird about the interaction between these two scripts. Why do *all* wood items in the game self-destruct and instantiate an item as soon as some variable of the global player inventory changes? However, you are not describing properly what this code is actually supposed to be doing, so maybe that's what you *want* it to do.
> 0 votes

# Answer
excuse me if this is totally wrong but i would start by making an 'array' for the inventory slots. then i would make a very simple option(if/else chain) for each item like equip, un-equip, and drop.

like:

```
#include <stdio.h>

int main()
{
     int inventory [9]; //int = data type, inventory = array name, 9 = size
     return 0;
}

```

as you approach a struct(item) have a string(some words) appear on screen

```
printf("item axe 50 damage : ");

```

if you want to pickup said item then

```
scanf("%d",&controller_button_1);

if (controller port == 1)
    printf("\nitem equiped is : %d ",item axe 50 damage);

```
> 0 votes

---
Tags: unity, c#, debugging, inventory
---