# Question
Title: preventing a camera from getting stuck inside a mesh in Unity
I've a 3rd person camera similar to Mario64. Currently, I'm working on preventing the camera from getting stuck inside a mesh. The goal is to move the camera overhead. This much trickier than I'd expected.

I've tried using a while loop but that crashes the game. The current code I'm using does this: https://youtu.be/-o1-LEb\_MZM

The code:

```
public class VCThirdPersonCamera : MonoBehaviour
{
    :
    :
    /// clipping variables
    /// use the camera's slider to determine defaultFOV
    public Vector3    cameraOffset = new Vector3(0,0.125f,-0.125f); //moves camera so player doesn't get clipped

    public float      fovDefault   = 60f;                           //the desired default field of view set by user
    public float      camTurnTime  = 0f;                            //use to compensate for the camera turning
    public float      headCamTimer = 1.5f;                          //how long should the camera stay overHead
    public float      fieldOfView  = 95.0f;                         //set when camera is overHead
    public bool       camOccluded  = false;                         //is the camera occluded
    public bool       clipped      = true;                          //used for clipping
    public Camera     _camera;
    public GameObject theCamera;

    private LayerMask   _mask;
    private RaycastHit  _hit;
    /// end occlusionHandlers

    private void Awake ()
    {
        :
        /// instantiate occlusion culling handler through bitSwitch
        _mask = 1 << LayerMask.NameToLayer("clip") | 0 << LayerMask.NameToLayer("clipNone");
    }

    private void LateUpdate ()
    {
        Vector3 targetCenter = _target.position + centerOffset;
        Vector3 targetHead = _target.position + headOffset;

        Vector3 theTarget = transform.TransformDirection(Vector3.forward)* 3.5f;
        Ray centerRay = _camera.ViewportPointToRay(new Vector3(.5f, 0.5f, 1f));

        if(Physics.Raycast(_camera.transform.position, theTarget, out _hit, 2.77f) && _hit.collider.CompareTag("Player"))
        {
            camOccluded = false;
        }
        if(Physics.Raycast(_camera.transform.position, theTarget, out _hit, 2.77f) && _hit.collider.CompareTag("environment"))
        {
            camOccluded = true;
        }

        /// creates ray from cameraViewPort to nearClipPlane
        float camClipPlane = _camera.nearClipPlane;
        /// sets up clipPoints from camera to viewPort
        Vector3 pos1 = _camera.ViewportToWorldPoint(new Vector3(0,0,camClipPlane));   //btmL
        :
        Vector3 pos8 = _camera.ViewportToWorldPoint(new Vector3(1,1,camClipPlane));   //topR

        bool clipLine01 = Physics.Linecast(cameraTransform.position, pos1, out _hit, _mask.value);
        :
        bool clipLine08 = Physics.Linecast(cameraTransform.position, pos8, out _hit, _mask.value);

        ///clip conditions are met & camera is occluded
        if((clipLine01)||(clipLine02)||(clipLine03)||(clipLine04)||(clipLine05)||(clipLine06)||(clipLine07)||(clipLine08))
        {
            camOccluded = true;
            //StartCoroutine(ResetCamera());
        }
        else
        {
            camOccluded = false;
        }

        if(!camOccluded)
        {
            Apply (transform, Vector3.zero);//default VCScamera method

        }
        else
        {
            StartCoroutine(ResetCamera());
        }
        print(camOccluded);
        print(headCamTimer);

    }
    public void OverheadCamera()
    {
        Vector3 targetCenter = _target.position + centerOffset;
        Vector3 targetHead = _target.position + headOffset;

        _camera.fieldOfView = fieldOfView;

        cameraTransform.position = (targetHead + cameraOffset) ;
        cameraTransform.LookAt(targetHead);
    }

    IEnumerator ResetCamera()
    {
        //camOccluded = true;
        OverheadCamera();
        yield return new WaitForSeconds(headCamTimer);
        _camera.fieldOfView = fovDefault;
        Apply (transform, Vector3.zero);//default VCScamera position
        camOccluded = false;
    }

    public void Cut ( Transform dummyTarget ,   Vector3 dummyCenter  ){
        float oldHeightSmooth= heightSmoothLag;
        float oldSnapMaxSpeed= snapMaxSpeed;
        float oldSnapSmooth= snapSmoothLag;

        snapMaxSpeed = 10000;
        snapSmoothLag = 0.001f;
        heightSmoothLag = 0.001f;

        snap = true;
        Apply (transform, Vector3.zero);

        heightSmoothLag = oldHeightSmooth;
        snapMaxSpeed = oldSnapMaxSpeed;
        snapSmoothLag = oldSnapSmooth;
    }

    public void SetUpRotation (Vector3 centerPos,  Vector3 headPos)
    {
        // Now it's getting hairy. The devil is in the details here, the big issue is jumping of course.
        // * When jumping up and down we don't want to center the guy in screen space.
        //  This is important to give a feel for how high you jump and avoiding large camera movements.
        //
        // * At the same time we dont want him to ever go out of screen and we want all rotations to be totally smooth.
        //
        // So here is what we will do:
        //
        // 1. We first find the rotation around the y axis. Thus he is always centered on the y-axis
        // 2. When grounded we make him be centered
        // 3. When jumping we keep the camera rotation but rotate the camera to get him back into view if his head is above some threshold
        // 4. When landing we smoothly interpolate towards centering him on screen

        //--------------------------------------------------------------------------//

        _camera.fieldOfView = fovDefault; // defaults camera to desired FOV

        Vector3 cameraPos = cameraTransform.position;
        Vector3 offsetToCenter= centerPos - cameraPos;

        // Generate base rotation only around y-axis
        Quaternion yRotation= Quaternion.LookRotation(new Vector3(offsetToCenter.x, 0, offsetToCenter.z));

        Vector3 relativeOffset= Vector3.forward * distance + Vector3.down * height;
        cameraTransform.rotation = yRotation * Quaternion.LookRotation(relativeOffset);

        // Calculate the projected center position and top position in world space
        Ray centerRay = _camera.ViewportPointToRay(new Vector3(.5f, 0.5f, 1f));
        Ray topRay = _camera.ViewportPointToRay(new Vector3(.5f, clampHeadPositionScreenSpace, 1f));

        Vector3 centerRayPos= centerRay.GetPoint(distance);
        Vector3 topRayPos= topRay.GetPoint(distance);

        float centerToTopAngle= Vector3.Angle(centerRay.direction, topRay.direction);

        float heightToAngle= centerToTopAngle / (centerRayPos.y - topRayPos.y);

        float extraLookAngle= heightToAngle * (centerRayPos.y - centerPos.y);
        if (extraLookAngle < centerToTopAngle)
        {
            extraLookAngle = 0;
        }
        else
        {
            extraLookAngle = extraLookAngle - centerToTopAngle;
            cameraTransform.rotation *= Quaternion.Euler(-extraLookAngle, 0, 0);
        }
    }

}

```

# Answer
> 1 votes
Every `fixedUpdate`, perform a `Raycast` from the player to the standard location of the camera where the maxDistance is the distance between player and standard location. When it hits a mesh, move the camera to the hit location. When it doesn't, move the camera to its standard location.

That way the camera will automatically move in and out based on the geometry ensuring that the player has a clear view on their character. A requirement for this is that everything which might obstruct the camera must have a Collider component which is at least as large as the mesh.

# Answer
> 0 votes
Found an easier solution by using volume colliders which which can be set up as zones for overhead cameras.

```
void OnTriggerStay(Collider thePlayer)
{
    if (thePlayer.gameObject.CompareTag ("headCamZone"))
    {
        OverheadCamera();
    }
    //followCamZone
    if (thePlayer.gameObject.CompareTag ("followCamZone"))
    {
        Apply (transform, Vector3.zero);//default VCScamera method
    }
}

```

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


# Question
Title: How to disable camera moves (mouse drag) in an Unreal Engine editor plugin?
I tried to override FEdMode:

```
virtual bool DisallowMouseDeltaTracking() const override
{
    UE_LOG(LogTemp, Warning, TEXT("do not allow mouse delta tracking!"));
    return true; // I also tried to return false
}

```

but the problem is that the cursor stops moving (and gets invisible).

Is it possible to change the camera moves (to make it like in 3Ds max or sketchup)?

# Answer
> 0 votes
I update the mouse position in the Render() function:

```
void FPBEdMode::Render(const FSceneView* View, FViewport* Viewport, FPrimitiveDrawInterface* PDI)
{
    MousePosition.X = FMath::Clamp(Viewport->GetMouseX(), 0, Viewport->GetSizeXY().X-1);
    MousePosition.Y = FMath::Clamp(Viewport->GetMouseY(), 0, Viewport->GetSizeXY().Y-1);
 }

```

and I reset the mouse position on mouse release (taken from FoliageEdMode.cpp):

```
bool FPBEdMode::InputKey(FEditorViewportClient *ViewportClient, FViewport *Viewport, FKey Key, EInputEvent Event)
{
    if (Event == IE_Released && Key == EKeys::LeftMouseButton)
    {
        Viewport->SetPreCaptureMousePosFromSlateCursor();
    }
}

```

---
Tags: c++, camera, mouse, unreal
---


title: Neural Network ai evolution?

text:
# Question
Title: Neural Network ai evolution?
I've created a small simulation game and I have a basic neural network in place, each "creature" in my game has random weights on it's nodes and they all behave differently.

Their goal is to stay inside a circular "safe zone" that moves around the center of the game world. After 1000 generations of evolution not a single one of them makes any attempt to follow the circle around, so I was thinking I either..

1. Don't know how to train them properly
2. Don't know how to find who should live/ die.
3. Using the wrong input/ outputs.

Here is the diagram of the brain (ignore the numbers)

Can anyone shed any light on what my issue is here? I'm sorry if this is vague I've only been using these for a couple of hours. But to elaborate on my question, what kind of inputs/ outputs should I be using with my neural network and what is the general procedure (in respect to my evolution approach) to train them to do the correct thing?? Could the error be caused by the number of nodes in the hidden layer or something?

# Answer
> 5 votes
I'm not entirely sure what the specific issue is with your setup, but there is a fairly in-depth explanation here of using a genetic approach to training neural networks.

One possible theory: generally in situations like games, NN's ability to learn patterns across long periods of time is limited. One way some people (like the author of the blog linked above) have gotten around this is to use recurrent neural networks .

RNNs are structured similarly to a regular feed-forward network, but they also have a set of 'context units' which (at each step) feed the previous values of the hidden units back into the hidden layer along with the new inputs from the input layer. By having this 'memory' of the previous hidden state, the model is able to detect patterns over a larger number of training steps.

I'm not entirely certain if this will solve your problem though. Perhaps someone else can comment on this?

---
Tags: java, ai
---


title: Why is Raycast hitting a masked layer?

text:
# Question
Title: Why is Raycast hitting a masked layer?
Many questions have been posted on this topic but I'm facing a weird behavior which I could not find an explanation for.

I perform a raycast giving it a `LayerMask` parameter which is defined as a public variable and set in the inspector with the layers "Wall" and "Enemy" ticked.

At first glance it appeared to work fine because the raycast rightly stops on GameObjects with that layer.

But then I saw that it also stopped on GameObjects set to the default layer, as if the LayerMask was ignored. Is there something I'm missing?

According to this answer I have set up everything correctly and I expected it to work fine.

Looking at the inspector at runtime I can clearly see that my mask is set only to "Wall" and "Enemy", and that the GameObject the collider is attached to has default layer set. I'm then stating that the mask the way I'm using it does not exclude other layers. The only way I can get this working is by setting that GameObject layer to Ignore Raycast, but in this case the LayerMask is not necessary.

I'm calling the function this way:

```
RaycastHit2D inSight = Physics2D.Raycast(start, end, lm);

```

Maybe is there something different with Physics2D and raycasts?
I would really prefer to use LayerMasks instead of specifying Ignore Raycast on whatever I want to ignore. Any clue?

# Answer
> 6 votes
I've had this happen with the 3D raycast in the past, and it seems to be because the raycast functions have so darned many optional parameters, and LayerMasks aren't picky about what type they're treated as.

From the docs:

```
public static RaycastHit2D Raycast(
       Vector2 origin,
       Vector2 direction,
       float distance = Mathf.Infinity,
       int layerMask = DefaultRaycastLayers,
       float minDepth = -Mathf.Infinity,
       float maxDepth = Mathf.Infinity
);

```

layerMask is the fourth parameter. So if you provide only three parameters, Unity wants to interpret them as origin, direction, and **distance**.

It might seem like providing an input of type `LayerMask` should make your intent unambiguous, or at least generate a compile-time error, but `LayerMask` can implicitly convert to `int`, and `int` can implicitly convert to `float`.

So when you put a LayerMask in the third argument, the compiler tries to convert it to a float, succeeds, and so silently re-interprets your mask as a distance. The fourth parameter `layerMask` is then unspecified, so it defaults to `DefaultRaycastLayers`, basically ignoring the layers you chose in the Inspector.

You can fix this by providing a dummy distance value (say, infinity, if you don't have any more conservative upper bound) so your layer mask selections end up in the fourth argument where Unity expects it:

`RaycastHit2D inSight = Physics2D.Raycast(start, end, float.PositiveInfinity, lm);`

---
Tags: unity, raycasting
---


# Question
Title: how to avoid circular references between objects and map
I've been working on a turn based tactics game on a grid. I've been trying to figure out how to store and relate the grid and the objects on it. Essentially, my question boils down to how to ask these two questions without violating the DRY(Don't Repeat Yourself) principle.

* Given a object, how to get it's position? `object.get_pos()`
* Given a cell, how to find out what object is in it? `grid.get_cell(cell)`

One particular thing I was thinking is that it doesn't make sense to talk about a object independently of the grid it is on. Therefore it seems like each object should have a reference to the grid. But having a grid doesn't make sense unless it has cells that contain objects. Is this just a place where things are tightly coupled enough that this kind of circular reference is acceptable?

# Answer
I think it makes sense for the two to know about each other. If you want to avoid tight coupling (and there are many good reasons to do so), you could have both the grid and the objects implement interfaces - IGrid and IGridObject, respectively. Then they can only refer to each other by interface, and that breaks the circular reference.

You may want to look into dependency injection (or some other inversion of control technique) and the factory pattern to help you on your way.
> 2 votes

# Answer
Circular referencing is usually not a good idea, and it's best to keep the flow in one direction - down. The grid and the objects have a parent-child relationship, whereby the grid is the parent, and the objects are its children. The question you should ask yourself is:

> Does the child need to know about or access information about the parent?

Does the object need to know about or access the grid? Typically, only the grid should have knowledge of and be able to access its objects, so it should have functionality to achieve both results:

* `grid.get_object(cell)` would return the object that is inside the specified cell.
* `grid.get_cell(object)` would return the cell that the specified object is in.
> 1 votes

# Answer
This is a perfect example of DRY being a concept that makes people afraid of making the right decision, in some cases. Here repeating yourself makes sense. Each cell should contain a list of objects in it and each object should contain the cell it is in. You will want both to correctly perform queries and operations. For example: given a list of common unit types, find all the cells they are in, or given a cell, find all the units in the surrounding grid cells. The key is to centralize the setting of these values in such a way that they are always synchronized. Using debug asserts in various places to confirm this is true is good engineering practices.
> 1 votes

---
Tags: tilemap, python, grid
---


# Question
Title: How to calculate faces involved in collision (Separating Axis Theorem)
I have a game engine created in javascript (https://jsfiddle.net/4gqsq8wf/) which uses collision detection via the Separating Axis Theorem. Currently, it does not have any means of resolving velocity upon the impact of multiple objects. Many posts have stated on this site that the post-collision velocity of an object is simply the angle of reflection. (For example: https://stackoverflow.com/questions/573084/how-to-calculate-bounce-angle) However, this requires knowing the angles of the surfaces contacting each other. I don't know how to figure out these, as the function I wrote only calculates the Minimum Translation Vector; how would I find the polygon faces involved in a collision?

Layman's terms would be appreciated.

Edit: Would this be the collision normal?

# Answer
> 1 votes
The Minimum Translation Vector is the collision normal most of the time.

However, I believe that without velocity information it is impossible to get the collision normal correct all the time. Consider that you have 2 aabbs colliding. One aabb is stationary. In one case, the other aabb moves from the left and hits the first aabb. The correct collision normal would be -x. In second case, the aabb moves from top and hits the stationary aabb. The collision normal would in in y axis. However, the 2 aabbs in both cases may land in the exact same position for your SAT test. And thus it is going to return the same MTV. As you see, you can get the same MTV despite having different correct collision normals.

If you really need collision normals, then you need a sweep test: such as this link: http://volgogradetzzz.blogspot.ca/2011/05/swept-sat.html.

Basically, with velocity information, we can calculate the time which each axis/edge of object is hit. Then the collision normal would be the latest time in which a axis/edge is hit.

# Answer
> 1 votes
My collision detection + reflection works just fine (see here). First you need a boundary box as you will have this already implemented. Boundary boxes are generally vertices having each in 2D an X and Y coordinate which define the outer structure of an object.

To generally calculate the angle of a boundary, I use in C++ an atan function, which returns the angle of a vector within a coordinate system:

```
double GetAngleofVector(vector2 aVec)
    {
    double angle = atan2(aVec.Y,aVec.X)
    return angle;
    }

```

However, sticking strictly to vectors , this is unnecessary and much easier to do with raw vector calculations. Now, if you have a collision detection in place (e.g. SAT), to calculate the reflection angle, you need to think of thee cases and their 'physics'.

A) a circle reflected against a circle B) a circle reflected against a boundary C) a boundary reflected against a boundary i) corner of Object 1 hits boundary of Object 2 ii) corner of Object 1 hits corner of boundary 2 iii) same as i, only reverse objects and hence calculations stay the same

There are good tutorials available for circle vs boundary (see e.g. here and here) and for rectangle vs rectangle with added rotation (see. e.g. here with Java Code sample).

For the simple case--bouncing of a wall, you need to get the projection of your velocity vector onto both the direction of the boundary and the direction perpendicular to the boundary. Call the boundary "colliding\_boundary", simply a vector of the two vertices that span it. (Construct your own vector class "vector2" with the float member variables x and y).

```
vector2 colliding_boundary;
colliding_boundary.x = vertice_2.x-vertice_1.x
colliding_boundary.y = vertice_2.y-vertice_1.y

```

To obtain the normal from any vector given, I use the standard formula. In 2D space that's relatively easy:

```
vector2 GetNormal( vector2 const &A )
    {
    return vector2(-A.Y,A.X);
    }

```

However, two more very useful formulas for 2D game engine development are the dot product and the unit vector along some original vector.

```
vector2 GetProjection(vector2 const &A, vector2 const &B)
    {
    vector2 dir=GetUnitVector(B);
    double p_length = DotProduct(A,dir);
    vector2 proj = p_length*dir;
    return proj;
    }

vector2 GetPerpendProjection(vector2 const &A, vector2 const &B)
    {
    vector2 dir=GetUnitVector(B);
    double p_length = DotProduct(A,dir);
    vector2 at = p_length*dir;
    vector2 an = A-at;
    return an;
    }

```

Finally, I apply two compact functions to obtain the two aforementioned projections of your object's original velocity vector.

```
vector2 GetProjection(vector2 const &A, vector2 const &B)
    {
    vector2 dir=GetUnitVector(B);
    double p_length = DotProduct(A,dir);
    vector2 proj = p_length*dir;
    return proj;
    }

vector2 GetPerpendProjection(vector2 const &A, vector2 const &B)
    {
    vector2 dir=GetUnitVector(B);
    double p_length = DotProduct(A,dir);
    vector2 at = p_length*dir;
    vector2 an = A-at;
    return an;
    }

```

Passing your velocity vector and boundary into those two functions gets you the two necessary vectors to get your object bouncing.

Remember, the resulting velocity is simply the reverse of the vector projection that is perpendicular to the wall (reflection!), while the velocity along the wall is kept.

So your final velocity would be:

```
vector2 v_final = GetProjection(speed_vector, colliding_boundary) - GetPerpendProjection(speed_vector, colliding_boundary).

```

For visualization I added a the demo link of my own game (mpeg) above. Notice the yellow, red, blue and white vectors being drawn at runtime collision and representing, in order, the object's original velocity, boundary perpendicular projection, boundary projection and final velocity. (Note, my object is also rotating, but ignore this for now.)

---
Tags: 2d, physics, collision-resolution, separating-axis-theorem
---


# Question
Title: Concerns about APK version compatibility
I'm making a game in Unity, and i want to know if I generate the apk in version 4.1 Jelly Bean he will run in newest versions of android? Can anyone explain me better how the version works?

# Answer
> 1 votes
**Yes it will work.**
if you set the game to 4.1 Jelly Bean it will work for the 4.1 and all the higher versions of android, here is a link for better explanation: https://www.udacity.com/course/viewer#!/c-ud853/l-1395568821/m-1643858570

---
Tags: android, unity
---


# Question
Title: (2D) Simple AI is not working when Object pooling is used
I am building a top down 2D plane game for practice. Here, enemy has an AI script attached. AI script does the following :

1. Determine whether the object is spawned to the left or right of screen.
2. If spawned to the left, rotate object by -90, move till a certain x position is reached, then turn down.
    3. If spawned to the right, rotate object by 90, move till a certain x position is reached, then turn down.

This works when I'm using Instantiate - Destroy method. But causes inconsistent behavior when I implement object pooling. Inconsistent behavior as in, 1\>Planes are spawned, 2\>Instead of moving a certain distance horizontally, they just turn down and move downwards. Sometimes they behave as intended, but other times, inconsistenct behavior.

Here is the AI script:

```
public class AI : MonoBehaviour
{
    float angle;
    Vector2 vel, turnVel;
    Rigidbody2D rb;
    bool leftSpawn, rightSpawn;

    void OnEnable ()
    {
        transform.rotation = Quaternion.Euler (Vector3.zero);
        rb = GetComponent<Rigidbody2D> ();
        turnVel = new Vector2 (0, -0.5f);
        if (transform.position.x < 0) {
            leftSpawn = true;
            transform.Rotate (0, 0, -90);
            vel = new Vector2 (1, 0);
        }

        if (transform.position.x > 0) {
            rightSpawn = true;
            transform.Rotate (0, 0, 90);
            vel = new Vector2 (-1, 0);
        }
    }

    void Update ()
    {

        if (leftSpawn && transform.position.x < -0.8f)
            rb.velocity = vel;

        if (rightSpawn && transform.position.x > 0.8f) {
            rb.velocity = vel;
        }

        if (rightSpawn && transform.position.x <= 0.8f) {
            rb.velocity = turnVel;
            angle = Mathf.LerpAngle (90, 180, Time.time * 0.9f);
            transform.eulerAngles = new Vector3 (0, 0, angle);
        }

        if (leftSpawn && transform.position.x > -0.8f) {
            rb.velocity = turnVel;
            angle = Mathf.LerpAngle (-90, -180, Time.time * 0.9f);
            transform.eulerAngles = new Vector3 (0, 0, angle);
        }
    }
}

```

Here is the spawning script that doesn't use Pooling. This works fine.

```
public class EnemySpawner : MonoBehaviour
{
    int turn = 0;
    public GameObject BF, JU, cam, Hawker, Blenheim;

    void Start ()
    {
        InvokeRepeating ("SpawnEnemy", 0, 3);
    }

    void SpawnEnemy ()
    {

        turn = Random.Range (1, 5);

        if (turn == 1)
            SpawnBF ();
        else if (turn == 2)
            SpawnJU ();
        else if (turn == 3)
            SpawnHawker ();
        else if (turn == 4)
            SpawnBlenheim ();
    }

    void SpawnHawker ()
    {

        float x = -4.47f, y;

        y = cam.transform.position.y + 4.59f;

        Vector3 pos = new Vector3 (x, y, 1);

        GameObject obj = (GameObject)Instantiate (Hawker, pos, Quaternion.identity);

    }

    void SpawnBlenheim ()
    {
        float x = 4.39f, y;

        y = cam.transform.position.y + 4.59f;

        Vector3 pos = new Vector3 (x, y, 1);

        GameObject obj = (GameObject)Instantiate (Blenheim, pos, Quaternion.identity);
    }

    void SpawnBF ()
    {
        float x = -4.47f, y;

        y = cam.transform.position.y + 4.59f;

        Vector3 pos = new Vector3 (x, y, 1);

        GameObject obj = (GameObject)Instantiate (BF, pos, Quaternion.identity);

    }

    void SpawnJU ()
    {
        float x = 4.39f, y;

        y = cam.transform.position.y + 4.59f;

        Vector3 pos = new Vector3 (x, y, 1);

        GameObject obj = (GameObject)Instantiate (JU, pos, Quaternion.identity);
    }
}

```

This is the script that pools Enemy planes:

```
public class EnemiesPooler : MonoBehaviour
{
    public static EnemiesPooler current;
    public GameObject BF, JU, Hawker, Blenheim;
    int pooledAmount = 10;
    List<GameObject> BFPlane;
    List<GameObject> JUPlane;
    List<GameObject> HawkerPlane;
    List<GameObject> BlenheimPlane;

    void Start ()
    {
        BFPlane = new List<GameObject> ();
        JUPlane = new List<GameObject> ();
        HawkerPlane = new List<GameObject> ();
        BlenheimPlane=new List<GameObject>();
        current = this;

        for (int i=0; i<pooledAmount; i++) {
            GameObject bf = (GameObject)Instantiate (BF,Vector3.zero,Quaternion.identity);
            bf.SetActive (false);
            BFPlane.Add (bf);

            GameObject ju = (GameObject)Instantiate (JU,Vector3.zero,Quaternion.identity);
            ju.SetActive (false);
            JUPlane.Add (ju);

            GameObject hawker = (GameObject)Instantiate (Hawker,Vector3.zero,Quaternion.identity);
            hawker.SetActive (false);
            HawkerPlane.Add (hawker);

            GameObject blenheim = (GameObject)Instantiate (Blenheim,Vector3.zero,Quaternion.identity);
            blenheim.SetActive (false);
            BlenheimPlane.Add (blenheim);

        }

    }

    public GameObject GetBF ()
    {
        for (int i=0; i<BFPlane.Count; i++) {
            if (!BFPlane [i].activeInHierarchy)
                return BFPlane [i];
        }

        return null;
    }

    public GameObject GetJU ()
    {
        for (int i=0; i<JUPlane.Count; i++)
            if (!JUPlane [i].activeInHierarchy) {
                return JUPlane [i];
            }
        return null;
    }

    public GameObject GetHawker ()
    {
        for (int i=0; i<HawkerPlane.Count; i++)
            if (!HawkerPlane [i].activeInHierarchy) {
                return HawkerPlane [i];
            }
        return null;
    }

    public GameObject GetBlenheim ()
    {
        for (int i=0; i<BlenheimPlane.Count; i++)
            if (!BlenheimPlane [i].activeInHierarchy) {
                return BlenheimPlane [i];
            }
        return null;
    }
}

```

Here is the script that spawns using Object Pooling. This is the one causing inconsistent behavior.

```
public class PoolTest : MonoBehaviour {
    int turn=0;
    float left=-4.47f,right=4.39f,yPos=4.59f,zpos=1,y,rotClockwise=270,rotCounterClockwise=-270;
    public Transform cam;

    // Use this for initialization
    void Start () {
        InvokeRepeating ("SpawnEnemy",0,3);

    }

    void SpawnEnemy()
    {

        turn = Random.Range (1, 5);

         if(turn == 1)
            SpawnBF ();
        else if (turn == 2)
            SpawnJU ();
        else if (turn == 3)
            SpawnHawker ();
        else if (turn == 4)
            SpawnBlenheim ();
    }

    void SpawnBF()
    {

        int spawnSide;
        Vector3 pos;
        float rot;

        y = cam.position.y + yPos;
        spawnSide = Random.Range (0,2);
        if (spawnSide == 0) {

            pos = new Vector3 (left, y, zpos);

        }
        else {
            pos = new Vector3 (right, y, zpos);

        }

        GameObject obj=EnemiesPooler.current.GetBF();
        if (obj == null)
            return;

        obj.transform.position=pos;
        obj.SetActive (true);
    }

    void SpawnJU()
    {

        int spawnSide;
        Vector3 pos;

        spawnSide = Random.Range (0,2);
        if (spawnSide == 0)
            pos = new Vector3 (left, y, zpos);
        else
            pos = new Vector3 (right,y,zpos);

        GameObject obj=EnemiesPooler.current.GetJU();
        if (obj == null)
            return;
        obj.transform.position=pos;
        obj.SetActive (true);

    }

    void SpawnHawker()
    {

        int spawnSide;
        Vector3 pos;

        spawnSide = Random.Range (0,2);
        if (spawnSide == 0)
            pos = new Vector3 (left, y, zpos);
        else
            pos = new Vector3 (right,y,zpos);

        GameObject obj=EnemiesPooler.current.GetHawker();
        if (obj == null)
            return;

        obj.transform.position=pos;
        obj.SetActive (true);

    }

    void SpawnBlenheim()
    {

        int spawnSide;
        Vector3 pos;

        spawnSide = Random.Range (0,2);
        if (spawnSide == 0) {
            pos = new Vector3 (left, y, zpos);
        }
        else
            pos = new Vector3 (right,y,zpos);

        GameObject obj=EnemiesPooler.current.GetBlenheim();
        if (obj == null)
            return;

        obj.transform.position=pos;
        obj.SetActive (true);

    }

    void Update () {
        y = cam.position.y + yPos;
    }
}

```

I have spent a lot of time trying to figure out what is causing this inconsistency. But, couldn't find any solution. Please help me. Thanks.

# Answer
> 1 votes
The trick about pooling complex/customizable objects is to reset their state before returning to a pool. So when you fetch from a pool, fetched object always be the same as instantiated one. I don't see any code that return object to pool.

I may suppose that when you init your pooler component some of AI get working before you disable objects. Between this two lines:

```
        GameObject bf = (GameObject)Instantiate (BF,Vector3.zero,Quaternion.identity);
        bf.SetActive (false);

```

Right after Instantiation of `bf` object `bf.OnEnable()` method was called causing the object to do some code and rotate. After that `bf.SetActive (false)` is called, but it's too late.

To check this out, add some debug code to your EnemiesPooler.Start() method:

```
void Start ()
{
    BFPlane = new List<GameObject> ();
    JUPlane = new List<GameObject> ();
    HawkerPlane = new List<GameObject> ();
    BlenheimPlane=new List<GameObject>();
    current = this;

    for (int i=0; i<pooledAmount; i++) {
        Debug.Log("Instantiation"); // here
        GameObject bf = (GameObject)Instantiate (BF,Vector3.zero,Quaternion.identity);
        Debug.Log("Instantiated. Deactivation"); // here
        bf.SetActive (false);
        Debug.Log("Deactivated"); // and here
        BFPlane.Add (bf);

        GameObject ju = (GameObject)Instantiate (JU,Vector3.zero,Quaternion.identity);
        ju.SetActive (false);
        JUPlane.Add (ju);

        GameObject hawker = (GameObject)Instantiate (Hawker,Vector3.zero,Quaternion.identity);
        hawker.SetActive (false);
        HawkerPlane.Add (hawker);

        GameObject blenheim = (GameObject)Instantiate (Blenheim,Vector3.zero,Quaternion.identity);
        blenheim.SetActive (false);
        BlenheimPlane.Add (blenheim);

    }

}

```

And in the AI.OnEnable() method:

```
void OnEnable ()
{
    transform.rotation = Quaternion.Euler (Vector3.zero);
    rb = GetComponent<Rigidbody2D> ();
    turnVel = new Vector2 (0, -0.5f);
    if (transform.position.x < 0) {
        leftSpawn = true;
        transform.Rotate (0, 0, -90);
        Debug.Log("Turned -90*"); // here
        vel = new Vector2 (1, 0);
    }

    if (transform.position.x > 0) {
        rightSpawn = true;
        transform.Rotate (0, 0, 90);
        Debug.Log("Turned 90*"); // and here
        vel = new Vector2 (-1, 0);
    }
}

```

After that run your code and you will see sequence of messages in the console. I suppose that between 'Instantiat**ion**' and 'Deactivat**ed**' will be 'Turned' message.

# Answer
> 0 votes
After some thinking, I decided to use the EnemySpawner script only to fetch planes. I moved the positioning logic to the AI script, so positioning, rotation and movement would be up to the spawned plane.

---
Tags: unity
---


# Question
Title: How to attach a framebuffer to a whole cube map from a GL_TEXTURE_CUBE_MAP_ARRAY?
I'm trying to make shadow cube maps in an array. I want to draw each shadow map with a single pass using a geometry shader, which I read about here: https://stackoverflow.com/questions/462721/rendering-to-cube-map. But in that example, the cube map is not in an array, and I can't find any code examples of how to get a cube map from an array attached to a frame buffer.

Just to make sure my array is legit, here's how I made it:

```
glGenTextures(1, &shadowMapArray);
glActiveTexture(GL_TEXTURE0 + TEXTURE_UNIT_SHADOW_MAPS_POINT);
glBindTexture(GL_TEXTURE_CUBE_MAP_ARRAY, shadowMapArray);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARRAY, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
glTexImage3D(GL_TEXTURE_CUBE_MAP_ARRAY, 0, GL_DEPTH_COMPONENT, POINT_LIGHT_SOURCE_SHADOW_MAP_RESOLUTION, POINT_LIGHT_SOURCE_SHADOW_MAP_RESOLUTION, (POINT_LIGHT_SOURCE_MAX_SHADOW_MAPS * 6), 0, GL_DEPTH_COMPONENT, GL_FLOAT, 0);

```

And this is how I tried to make the frame buffer:

```
    //Create the shadowMapFrameBuffer
    glGenFramebuffers(1, &shadowMapFrameBuffer);
    glBindFramebuffer(GL_FRAMEBUFFER, shadowMapFrameBuffer);
    glDrawBuffer(GL_NONE);

    //Attach the shadow map to the shadowMapFrameBuffer
    glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadowMapArray, 0, shadowMapIndex);

    GraphicsResources::checkGLFramebufferStatus();
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

```

But it looks like glFramebufferTextureLayer is only going for a layer-face, not a layer (a whole cube map), so only the first face (positive X) of the first shadow map is working, (and, for some unknown reason, only half of that face).

I also tried this:

```
    glFramebufferTexture3D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_POSITIVE_X, shadowMapArray, 0, ((shadowMapIndex * 6) + 0));
    glFramebufferTexture3D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_NEGATIVE_X, shadowMapArray, 0, ((shadowMapIndex * 6) + 1));
    glFramebufferTexture3D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_POSITIVE_Y, shadowMapArray, 0, ((shadowMapIndex * 6) + 2));
    glFramebufferTexture3D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, shadowMapArray, 0, ((shadowMapIndex * 6) + 3));
    glFramebufferTexture3D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_POSITIVE_Z, shadowMapArray, 0, ((shadowMapIndex * 6) + 4));
    glFramebufferTexture3D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, shadowMapArray, 0, ((shadowMapIndex * 6) + 5));

```

But I don't know if a frame buffer is meant to be set up with multiple calls like that, and anyway, this produces 'GL\_INVALID\_ENUM'.

Anyone know the proper way to do this?

# Answer
I hate seeing workarounds instead of real answers, but I've come to the conclusion that the current OpenGL spec doesn't provide the functionality that would answer this question, and I have found a workaround:

Rather than making a small frame buffer for each cube map, I made a big one for all of them with a simple call to glFramebufferTexture:

```
glFramebufferTexture(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, shadowMapArray, 0);

```

Then to access a specific cube map for rendering, I passed the index of its first face to a uniform in the geometry shader, and assigned it to `gl_Layer` and rendered to that and the next 5 layers.

This created a problem with clearing the shadow map I wanted to update - the single frame buffer can only clear all of them at once, wiping the ones that aren't getting updated. My solution for this was to make 6 single face frame buffers for each cube map using `glFramebufferTextureLayer`, and clearing those instead. It seems a little awkward and redundant, but it works.
> 2 votes

---
Tags: opengl, shadow-mapping, cubemap, frame-buffer, rendertexture
---


# Question
Title: Unity 3d Forge Networking: Transfer object ownership
I have a simple chess game setup to play around with the Forge Networking asset. I am having an issue where only the server is able to click and drag pieces around the board. If a client attempts to move a piece, it gets snapped back to its original position.

I assume this issue is because the server is the actual owner of the `NetworkedMonoBehaviour` components on my chess pieces. Is it possible to transfer ownership of a `NetworkedMonoBehaviour` in code? It seems that all of the owner properties have protected set methods so I am unable to access any of them.

# Answer
So when you have objects already in the scene in Forge Networking it is automatically owned by the server. Any objects that are instantiated by the client is owned by the client. Something you can do is either spawn the objects on the client or you can use an RPC call to move the object. So you would move the piece and drop it, then when you drop it you would send an RPC call to place it and the server can then validate. Transferring ownership is something that has been requested in the system a couple of times and it is on the feature add list for future versions. :)
> 1 votes

---
Tags: unity, networking
---


title: How do you structure an Item class?

text:
# Question
Title: How do you structure an Item class?
I've been thinking about the structure of an Item class. There are many items which may or may not have effects in the game.

For example, an item "Herb" has an effect to "Heal HP by 5". but an item "Stone" has no effect.

As per a title, when you design a game, how do you structure the Item class?

The following is the structure I've come up with.

```
class Item{
    String id;
    // Status where s = HP, MP, ATK .. etc
    // Integer -> value which affects on the Status
    Map<Status, Integer> effect;
    SignType st; // +, -, *, /
}

class Player{
    Map<Status, Integer> status; // Status where s = HP, MP, ATK .. etc
}

```

# Answer
Have one base class Item. Then create two sub class, one for Items with effect and another for Items without effect, like this-

```
class Item {
    String id;
}

class EItem extends Item {
     Map<Status, Integer> effect;
     SignType st;
}

class WEItem extends Item {
}

```
> 2 votes

# Answer
If you want to keep things simple and each item independent, your current solution looks good. However, you only need addition and multiplication, the other two can be built with inverse operands.

In the long term, the question is if a set of predefined operations is flexible enough. What if a developer wants more sophisticated conditions, e.g.

> If the item owner carries a sword, triple his attack damage.

In that case, you would need access to other items, possibly through a query interface. However, as soon as you use dynamic code, you can't easily serialize it anymore.
> 0 votes

# Answer
Remember that object oriented programming is usually using some form of data structure. It is probably easier to think of it in that format.

So... when creating an item. A common implementation is to just make an "onUse" function. Which... is ok, but kinda pointless. The item may have more than one effect. So... lets make it more interesting.

```
Class Item : {
  private:
    array<Action> ActionList;
  public:
    AddActions<Action>;
    Use(Target, Target2 = NULL){
         for( However many actions in action list)
              ActionList.onUse(Target, Target2)
    };

}

```

Here, our item has a target and an action list. The target is who the item is being used on. Of course you can always pass an array for multiple targets.

So...now the action list. What is an action list? If you are familiar with components, then it is basically the same thing. Action Lists are modules of code with data that is created on instantiation via factory or something.

First the interphase.

```
Class Action {
    virtual update(Target, Target2 = Null) =0;
}

```

Next the implementation.

```
Class RestoreHP : Action {
   private:
     _healthRestore;
   public:
     RestoreHP(HealthRestore);
     Override onUse(Target, Target2 = Null);
}
Class AddShield : Action {
   private:
     _shieldStrength;
     _shieldDuration;
   public:
     AddShield(ShieldDuration, ShieldStrength)
     Override onUse(Target, Target2 = Null);
}

```

When you make a new item. You add a series of Actions into it's array, and run through them.

For example... we want to make a heroic potion? Well The action list contains a heal and a shield module.

The benefit to the design is simplicity, easy to define archetypes. Easy to add more modules.

Also remember that you do not need to rebuild this class for each object of the same item. You only need to hold a reference, as the item class does not hold position.
> 0 votes

---
Tags: java, game-design
---


# Question
Title: How to choose and scale heuristics for A-star on a graph?
I am trying to find the best and scale my cost function for my algorithm. I am following amit blog which explain that (http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html#manhattan-distance).

I have a humanoid character first blue circle is the start configuration with the left foot (red). Then I expand a set a possible right footsteps (blue) and again with the left foot (red) until the center of the character reach the goal.

my heuristic look like : f = g + h;
with `g` = g + oneStepCost (distance between 2 footsteps) + TerrainCost (0 free, Infinity if obstacles); // Cost to go
`h` = distance between the middle of the character and the goal;

What do you think about this basic heuristics ? I feel using the Euclidian distance is the best suited for my configuration but Manhattan distance seems a lot faster.

On amit blog, he says that it is good to have a cost function = 1 for the minimum distance traveled but I don't really understand how to do that because my cost function is in meters.

Then, i might have lot of paths which are almost the same length. So, I have to break ties. So, if I use this formula : h \*= (1.0 + p) with p \<(minimum cost of taking one step)/(expected maximum path length) . For my case, minimum cost of taking one step = 0.10 m and maximum path length = (0.25 meter * 12 steps). Does it seems correct to you ? Any others tips in order to improve heuristics and not spending time for the path with almost the same length ?

# Answer
> 1 votes
manhattan vs euclid is just 2 extra multiplications and a square root. That is not worth worrying about.

What is important is that the heuristic underestimates the remaining path. This means that the heuristic must be equal or less than the actual shortest path from the current node to the destination.

Instead of calculating in meters you can calculate in decimeters (1 dm = 0.1 m). Any arbitrary linear scaling function can do but it's not really necessary.

---
Tags: c++, path-finding, optimization, graph, heuristics
---


# Question
Title: Unity + Texturepacker: Pivot point in weird positions
When my designer sends me the spritesheets done with Texturepacker and I open them with the Sprite editor, i notice that the pivot point is in extremely weird positions. Way above the spritebox that it is attached to.

I told him to put the pivot point "Bottom center" instead "center", and the pivot moved to positions not so exagerated, but still outside the spritebox.

I thought that someone (my designer or me) had something misconfigured, but then I opened the example spritesheet that came with Texturepacker, and I noticed that the pivot point was also in weird positions

As you see the pivot point is under the spritebox. And as I say, this is because the pivot point is set to "Bottom center". If I set it to "Center", it goes even weirder positions.

What is going on? Is something misconfigured here?

# Answer
> 2 votes
This is as it should be - no bug ;-)

TexturePacker has 2 crop modes in Unity - to remove transparency around the sprites which consumes memory and GPU.

* Trim Keep Pos - removes the transparency but keeps the pivot point in the position where it was in the original sprite
* Trim Flush Pos - removes the transparency and sets the pivot point relative to the cropped sprite

The default is "Trim Keep Pos" since this allows you playing the animations without jitter if all frames had the same size and were aligned before the crop. In Unity's sprite editor it seems that the pivot point is off - but that's perfectly ok.

See this image:

The gray area is the original sprite, the black rectangle the trimmed. As you see the red pivot point is outside the rectangle - but in the center of the original sprite.

---
Tags: spritesheet, unity
---


# Question
Title: Optimize drawing "different" sprites in OpenGL ES 2.0 (batching?)
I started experimenting with OpenGL ES 2.0, and I'm trying to figure out a way to optimize/batch sprite drawing, where sprites only have the texture in common, but differ in the following properties:

* Position
* Size
* Rotation
* Texture coordinates
* Color
* Hue

I tried two different approaches, which are "good enough" for most games, but I'm still curious on how I could optimize drawing sprites further. All the code is available here on GitHub, but I'll explain my approaches below.

(Both approaches use *4 vertices + 6 indices* to draw a quad.)

1. **One drawcall per sprite.**

Position and texture coordinates are passed as a `vec4` vertex attribute. The MVP matrix (that handles size and rotation) is passed as a `mat4` uniform. Color is passed as a `vec4` uniform and hue is passed as a `float` uniform.

Since pretty much everything is being passed as an uniform, I have to set all uniforms and call `glDrawElements` once per sprite.

I can draw 50000 sprites at 60FPS on my desktop (i7 2400k, GTX 970).
2. **One drawcall per `N` sprites.**

The second idea I had and tried was dividing sprites in batches of `N`. In this approach, everything is passed as a vertex attribute.

```
 attribute mat4 a_projection_view_model;
 attribute vec4 a_pos_tex_coords;
 attribute vec4 a_color;
 attribute float a_hue;

```

From my tests it seems slightly faster than the previous approach, but it isn't a big improvement. Also, passing the same `mat4` and the same `vec4` (`a_color`) four times seems weird and unnecessarily expensive.

I couldn't figure out a different solution since every sprite has its own MVP matrix, color an hue.

How is sprite batching (when the texture is the same) usually done? Are my approaches "correct" in theory, or am I doing something which is considered bad practice?

How can I optimize my sprite drawing?

# Answer
> 2 votes
The typical situation is that all sprites are rendered with the same view/projection matrices (same "virtual camera").

So the way I see it, all your sprites need just one draw call - just generate all the vertices on the CPU:

* Multiply vertex positions of each sprite with the model matrix
* Pass view\*projection as MVP matrix
* Calculate final color for the sprite on CPU, write it to each vertex (so color becomes a vertex attribute)

P.S.

> I couldn't figure out a different solution since every sprite has its own MVP matrix, color an hue.

Why would you possibly need one MVP matrix for *each* sprite and color+hue (instead of just color)?

# Answer
> 1 votes
You should probably avoid the first method. One draw call for just four vertexes is suboptimal. It might work on a bulky desktop PC, but will certainly be very slow on a mobile device.

One solution that I have been using as of late and like it, is to generate the 2D vertexes on the CPU-side and pass them to the shader. Each vertex is comprised of whatever shading attributes you may need (tex-coords, color, position, whatnot), then my Vertex Shader is basically just a pass-through. I also convert the 2D vertexes to OpenGL clip space, since I'm already calculating the final vertex position in the CPU, this is a cheap operation, so my typical 2D sprite drawing Vertex Shader looks something like this:

```
in vec3 inPosition;
in vec2 inTexCoords;
in vec4 inColor;

out vec2 vTexCoords;
out vec4 vColor;

void main()
{
    gl_Position = vec4(inPosition, 1.0);
    vTexCoords  = inTexCoords;
    vColor      = inColor;
}

```

That avoids the need of supplying different matrices via uniforms, which facilitates batching. My only batching criteria is the texture applied to the sprites, so I only need **one draw call per texture**. This can be further optimized if you use *texture altases* to pack small textures into a larger one.

This is similar to the approach proposed by @snake5's answer.

---
Tags: opengl, graphics, sprites, opengl-es2, optimization
---


# Question
Title: How is a 3d perlin noise function used to generate terrain?
I can wrap my head around using a 2d perlin noise function to generate the height value but I don't understand why a 3d perlin noise function would be used. In Notch's blog, http://notch.tumblr.com/post/3746989361/terrain-generation-part-1, he mentioned using a 3d perlin noise function for the terrain generation on Minecraft. Does anyone know how that would be done and why it would be useful? If you are passing x,y, and z values doesn't that imply you already have the height?

# Answer
2D perlin noise is good for height maps, but in this case it seems that he is not using a height map. Instead he has a 3D grid, where any cell can be empty. This allows caves and such formations, where the ground height is not a single value for given 2D location.
> 20 votes

# Answer
> Instead of sampling the “ground height”, I treated the noise value as the “density”, where anything lower than 0 would be air, and anything higher than or equal to 0 would be ground.

Simply put, for every place where a block can be, a noise function is evaluated, and if it is \>0, a block is placed. Notch's noise function is skewed by adding height from water level to its value, that's why lower areas are mostly solid (height is large negative, so height+noise is negative too) and higher areas are mostly empty (height is large positive, so height+noise is positive too).

There's probably some additional alchemy to decide what *kind* of block gets generated, and to carve caves. But I guess it's not directly related to this noise function.

Also note that this method works for Notch because Minecraft has a voxel-based terrain. If you tried to pull that off in a polygon-based world, simply sampling noise function would not be enough. You' have to use some algorithm to turn samples into a surface, and create polygons that approximate this surface. One such algorithm is marching cubes.
> 16 votes

# Answer
3D noise becomes mandatory if the terrain needs cave networks and overhangs.

To extract an isosurface from density information, the 2 most popular techniques are Marching Cubes (MC), and the newer Dual Contouring (DC). The data structure needed is quite different depending on the chosen method.

As previously mentioned, Geiss's GPU Gems 3 article is a very instructive starting point for understanding and implementing MC terrains on the GPU (Note that his MC approach run entirely on the GPU and requires at least SM4 - GS- capable one).

Because density data on MC voxels can only stay on voxel's edges, classic MC may contour the volume without preserving sharp edges features. DC does not suffers this drawback since the density info is expressed as a 3D point (QEF minimizer) laying anywhere inside the voxel plus the sign at each corner.

On the other hand, MC does not suffer from self-intersecting faces because all generated triangles are enclosed in their corresponding voxels, whereas DC needs additional computations to prevent intersections between generated faces. DC authors addressed this issue in an improved version of their algorithm.

http://www.cs.wustl.edu/~taoju/research/interfree\_paper\_final.pdf

http://www.cs.berkeley.edu/~jrs/meshpapers/SchaeferWarren2.pdf

This fellow also propose a likely cleaner approach based on convex / concave analysis for avoiding self-intersections. He uses as well better quad splitting rules to help preserve edge's orientation:

http://www2.mae.cuhk.edu.hk/~cwang/pubs/TRIntersectionFreeDC.pdf

Classic MC is also not out-of-box "crack-free" and may require crack patching if ran on unrestricted octrees. DC does not suffer from this last issue.

Here is a pretty nice and complete survey of most mesh extraction techniques : http://www.cs.berkeley.edu/~jrs/mesh/

An octree / voxel approach is intrinsically "CSG-friendly", which make it easier to plan a neat fully "destructible" game level strategy, but if one needs to implement all this in a game, the octree depth will also need to be frustum-dependent.

If the whole stuff fits in memory or is correctly streamed, the data can also be used for rendering AO and computing physics / collisions.
> 8 votes

# Answer
My guess, in that particular example, is that he used the z value to determine what type of material: bedrock, stone, dirt, or air.
> 5 votes

# Answer
Minecraft uses the marching cubes algorithm to generate 3D terrain. I don't have a refernce for this, I'm sorry. I'm not sure exactly what Notch was talking about when he mentioned the Perlin Noise function - perhaps a seed for the marching cubes algorithm. More info here:

And a great GPU Gems article if you're interested in marching cubes:
> -3 votes

# Answer
```
for (int x = 0; x < Width)
{
  for (int y = 0; y < Depth)
  {
    for (int z = 0; z < Height)
    {
      if(z < Noise2D(x, y) * Height)
      {
        Array[x][y][z] = Noise3D(x, y, z)
      } else {
        Array[x][y][z] = 0
      }
    }
  }
}

```
> -6 votes

---
Tags: procedural-generation, terrain, minecraft-modding
---


title: Sending block chunks through TCP

text:
# Question
Title: Sending block chunks through TCP
I am creating a 'Minecraft clone' and the game is going to be only multiplayer. I currently have a limited world (it's not going to be infinite) that is *512* chunks.

Each chunk is *16(X)* * *16(Z)* * *128(Y)* of blocks.

Each block is represented by a byte. This means I have a 3D array of bytes that represents which block is in which position in the chunk (*0 means Air*). I got to the part where I want to send the world though the TCP connection.

I am using *KryoNet* for my multiplayer needs. Currently what I do is I flatten the 3D array to the highest Y coordinate that is not air, making my (16 * 16 * 128) array into a (16 * 16 * *less than 128*) array. After doing this I take the 3D array and flatten it into a 1D array. After doing that I have a 1D array of size *~32,000*. Obviously sending the entire *32KB* of data through the connection at once is stupid and it also crashes *KryoNet*.

My question is how would I efficiently go about sending *512* chunks (512\*32 KB of data) through the connection?

I thought about separating the 1D array (*32,000* bytes) into 32 packets each of 1KB of data but it seems odd to send 512 * 32 packets to send the world (*~16,000* packets). Is there any way to compress this data or send it in a more efficient way through my TCP connection? Obviously this is done once per session but still *16,000* seems a lot.

**Progress update:**

I have separated the chunks into 33 packets each, and I send them one after the other. It seems to be working well, but I have a slight ordering issue that is unrelated. At the times that it works it loads quite quickly and with no problem! If there is a more efficient way of going about this please do post it here!

# Answer
Besides splitting up the data in multiple packets as you've already proposed, you could try 2 more things:

The first (and simplest) is to do run length encoding on the data.

Run length encoding is when, instead of saying "Stone,Stone,Stone,Air,Air,Air" you say "3,Stone,3,Air". In typical minecraft style maps that saves a *lot* of data and it is used in most games like it.

Besides run length encoding, if you're dealing with this much data, and data for which latency isn't *that* big a deal, try using a generic compression algorithm!

Java already has an implementation for GZIP, try sending the data to a memory buffer via a GZIPOutputStream and sending that data, it should be a lot smaller. (Speed wise, this is something that can rather easily be done in another thread so it shouldn't affect the game much)
> 1 votes

---
Tags: multiplayer, minecraft-modding, data
---


# Question
Title: How can use a 3D map with 2D characters (Unity)?
I tried to search something about it but I can't find any complete or well-explained tutorials about how to use a 3D map with 2D characters and items, like Ragnarok or Final Fantasy Tactics.

If there is no tutorials about this topic, are there any recommendations for studying the subject? I've already developed some games using XNA, but only 2D games, I've never tried to use 3D models, nor have I used Unity to develop games.

# Answer
There is nothing stopping you from using 2D sprites in a 3D world.

Unity has support for 2D, 2.5D and 3D in all combinations of the set together.

*"I want 3D models in a 2D game."* \- Fix the camera to a pan only system and use 3D models.

*"I want 2D models in a 3D game."* \- Fix the camera to follow a 2D sprite but use the 3D character controller.

Try it. If it doesn't work or you have issues along the way, come back and we can help!
> 2 votes

---
Tags: unity, 2d, 3d, maps
---


# Question
Title: Why am I getting these artifacts when rendering polygons with OpenGL and SDL from far distance?
I'm working in a toy BSP (quake3 version) renderer. I started creating the context and handling the input with GLFW but then I switched over SDL. The performance change was amazing with SDL leading with 100+ fps.

But when rendering some surfaces from far now I'm getting some strange and ugly artifacts in the borders or junctions. The only thing that I changed from GLFW to SDL was the initialization (code bellow) and the input handling but the OpenGL Draw calls are the same.

Why am I getting these artifacts when rendering polygons with OpenGL and SDL from far distance?

This only happens with some surfaces (mostly the ones without textures, only vertex colors) but there are some tiny surfaces (pendants or flags) that also have the same problem. Also, not all the borders of the same faces have the problem.

```
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0) {
    cout << "Failed to init SDL Video" << endl;
};

SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS,   SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);

_window = SDL_CreateWindow("BSP Test", 0, 0, width, height,
                            SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);

if (_window == nullptr) {
    SDL_Quit();
    return false;
}

SDL_GLContext ctx = SDL_GL_CreateContext(_window);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

glGetIntegerv(GL_MAX_PATCH_VERTICES, &ee);
cout << "Max patch vertices : " << ee << endl;

glPatchParameteri(GL_PATCH_VERTICES, 9);

cout << "GL ERROR LOAD  :" << glGetError() << endl;

glClearColor(0.0f, 0.0f, 0.01f, 1.0f);

glEnable(GL_CULL_FACE);
glCullFace(GL_BACK);
glFrontFace(GL_CCW);
glEnable(GL_DEPTH_TEST);
glEnable(GL_MULTISAMPLE);
glEnable(GL_POLYGON_SMOOTH);
glEnable(GL_LINE_SMOOTH);

SDL_GL_SetSwapInterval(0);

matrices.proj = glm::perspective(glm::radians(100.0f), (float) width / (float) height, 1.0f, 4000.0f);

camera.position = glm::vec3{-41.415211f, 320.293121f, -537.225281f};

return true;

```

# Answer
> 2 votes
As @bcrist pointed out, the depth buffer bits is set by default to 16 with SDL. changing that value to 24 or 32 solved the problem, giving more precision to the depth test.

```
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);

```

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


title: Unity doesn't show always the score

text:
# Question
Title: Unity doesn't show always the score
I don't know if this issue is in Unity or in my script, the score work well in scoreText, but in the scorePanel its show before last score like it showing 1 rather than 2; **the issue doesn't always appear its appear just in specific moment when my score++ and player die nearly in same time**, so here is my script. AddToScore is called with InvokeRepeating, scoreText who show me the correct score, it works well

```
void AddToScore(){
    score++;
    scoreText.text = score.ToString ();
    mySound.Play();
}

```

This is when my player Die

```
void OnCollisionEnter2D(Collision2D other)
{
    Time.timeScale = 0;
    Die ();
}

void Die (){
    Pause.SetActive (false);
    Panel.SetActive (true);
    GameOverPanel.SetActive (true);
    GenerateObstacles.HighScore ();
}

```

And here is the HighScore from GenerateObstacles

```
public void HighScore(){
    if (score > highScore) {
        PlayerPrefs.SetInt ("highScore", score);
        highScore = PlayerPrefs.GetInt ("highScore");
        scorePanel.text = score.ToString ();
        highScorePanel.text = highScore.ToString ();
    }
    else if (score <= highScore) {
        highScore = PlayerPrefs.GetInt ("highScore");
        scorePanel.text = score.ToString ();
        highScorePanel.text = highScore.ToString ();
    }
}

```

Here is a paint to understand

# Answer
When player dies, Time.timescale is set to zero. So, you are stopping your application's clock. So time doesn't pass and AddToScore() will not be invoked.
> 2 votes

# Answer
Looking at this: `GenerateObstacles.HighScore ();` It's not clear how the class is designed. HighScore() is not declared static. It would look like GenerateObstacle is a static reference, but it is not. One way is to declare a static reference in GeneratedObstacles like this : `public static GeneratedObstacles current;` then, in Awake(),

`void Awake(){
current=this;
}`

With that, your code would change to : `GeneratedObstacles.current.HighScore();`
> 0 votes

---
Tags: unity, text, scoring
---


# Question
Title: why doesnt this function work? glsl opengl c++
Im trying to move a transformation matrix onto the gpu, and I managed to find this code to help me on the way:

vertex.shader:

```
#version 410 core
layout ( location = 0 ) in vec3 vertex_position ;

mat4 rotationMatrix(vec3 axis, float angle)
{
    axis = normalize(axis);
    float s = sin(angle);
    float c = cos(angle);
    float oc = 1.0 - c;

return mat4(oc * axis.x * axis.x + c,           oc * axis.x * axis.y - axis.z * s,  oc * axis.z * axis.x + axis.y * s,  0.0,
            oc * axis.x * axis.y + axis.z * s,  oc * axis.y * axis.y + c,           oc * axis.y * axis.z - axis.x * s,  0.0,
            oc * axis.z * axis.x - axis.y * s,  oc * axis.y * axis.z + axis.x * s,  oc * axis.z * axis.z + c,           0.0,
            0.0,                                0.0,                                0.0,                                1.0);
}

void main()
{

gl_Position=rotationMatrix(vertex_position,45.0);

}

```

However, this gives errorc1035: assignment of incompatible types. Shouldnt this work? What am I missing

# Answer
gl\_Position expects a variable of type vec4 and you're giving it mat4. So you need to multiply your rotation matrix by the vertex position and return the resulting vector. Something like:

```
gl_Position = rotationMatrix(axis, angle) * vec4(vertex_position, 1.0);

```
> 0 votes

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


# Question
Title: Unity3D: Storyboard-esq animation - a beginners question
As part of an interactive book I'm developing in Unity3D, I'm attempting to make an introductory scene that consists of moving lots of objects at different times - usually when another animation has completed.

For example, some trees (sprites) move down the page, which starts some text moving in and cloud sprites to appear and start to move across the page, then some text begins to scroll from the bottom to the top of the page, while some audio beings to play.

Currently, I've made a script that can move a series of clouds from left to right, or right to left across a background sprite given a speed (note: I'm not using any of the animation tools, simple C# scripting to move the objects on a loop).

Within Unity3D, what is the recommended approach to achieve this?

My thoughts are:

1. Create a series of scripts that waits for *n* seconds (where *n* is the duration a desired 'animation'), and then start another - with somekind of 'master' or 'controller' script to manage the timeline.
2. Somehow use the animation tooling built into Unity3D, although I don't think that this what they were indented for...
3. Find a plugin that can help me create the scene and trigger animation/ scripts either on an event (animation finished) or after a specific time.

I've been using Unity3D for about 2 weeks now, so I'm certainly at the (pre?)-beginner level, I do however have over a decade of C# experience, so I'm comfortable with the scripting aspect.

Thanks in-advance,
Kieron

# Answer
> 0 votes
Just revisiting this after a while, I've found that the Fungus Framework on the Asset Store was just what I needed.

# Answer
> 2 votes
I once needed to do this, to have several "animations" play off one after the other, here's my approach :

1- Create an empty gameObject, let's call it `SceneControl` that will be the parent of everything you need animated in your scene, for example Trees, which will contain all the trees, Clouds, that will contain all the clouds, Text, etc..

2- Set all the childs of `SceneControl` as inactive, from the Editor.

3- Make a script that you will then attach to `SceneControl`. In this script, you can choose whatever you like to do with the children :

A time loop that waits for X seconds to start childs sequence, rough example of this :

```
if( SceneControl.childCount > i) {
      if(Time.time - elapsedTime > X) {
      this.transform.GetChild(i).SetActive(true);
      i++;
      elapsedTime = Time.time
      }
}

```

This is automated to run every time the counter reaches X seconds, and it will start the next object on the order of the children of `SceneControl`, (make sure to declare SceneControl in Start()). You can otherwise choose whatever to do with the objects, and whenever to control them according to your needs, the basic idea is to make them all inactive, and set them to become active, after X second passes, after animation ends, after (insert condition here).

---
Tags: unity, 2d, animation, storyboard
---


# Question
Title: (2D) Take player speed into account while shooting bullets
In my top down 2D game, there is a plane as shown below:

The plane shoots bullets forward. For firing bullets, I use:

```
obj.GetComponent<Rigidbody2D>().AddForce(transform.up*500);

```

However, when player presses up arrow or A key, plane speed increases. At this point, bullets are slower than the plane and appear to move backwards when plane moves at maximum speed.

How do I take into account player speed so that force applied takes into account player speed?

# Answer
There are lacking of code, however I would suggest that the bullet `obj` is a result of the method `Instantiate`. If it so, you should just inherit velocity of the plane right after instantiation and before adding force.

```
GameObject obj = Instantiate(bulletPrefab, plane.tranform.position, plane.transform.rotation) as GameObject;
Rigidbody2D rb2d = obj.GetComponent<Rigidbody2D>();
rb2d.velocity = plane.GetComponent<Rigidbody2D>().velocity;  // set bullet's velocity equal to 'source' velocity
rb2d.AddForce(transform.up * 500);  // and then add force

```

Also, you can play around with ForceMode2D and optionally try Rigidbody2D.AddRelativeForce to get desired/unusual effects.
> 2 votes

---
Tags: unity
---


# Question
Title: Find shortest path (quickly) on the surface of a 3d model?
Imagine this scenario: we have a 3d model, for instance a doughnut, apple or an orange (possibly something more complex). There's an insect (let's say an ant) on the surface of that food item. Now that ant wishes to reach a certain specific coordinate embedded on the surface of the 3d object in the shortest time possible (using the shortest path, ignoring physics).

Now the ant AI could use Dijkstra on the original mesh but that might be low-res so the ant will zig-zag on the surface, outlining the shapes of *blocky* faces. You could split the faces but the angular nature of the edges, making up the structure of the mesh will continue to drive the ant to more in ziggy-zaggy like manner (imagine a rougelike with very small squares, you can still only move in 8 directions at any given point).

What we did is split the edges (of the model) to evenly-sized pieces and embedded "navigation vertices" between these pieces, we then connected the vertices of each edge with vertices of other edges sharing a face with it (4 other edges because faces are triangular). This works pretty well cause it means the any can travel freely between faces, ignoring their shape almost completely (unless they are very small and were not split).

We also have the ant "pulled" (dragged even) by an imaginary ant that is a few steps ahead to completely eliminate the more rigid areas in the path (think sharp corners). Sounds great right?

But this is not terribly fast. Any advice about that is appreciated.

# Answer
> 4 votes
Precalculate triangle adjacency data, then what you'll have will basically be a navigation mesh. Any pathfinding algorithm (like A\*) will be able to work on that.

That's of course assuming the mesh doesn't have 3 or more triangles sharing the same edge, things could look strange in that case. All connections except the topmost would have to be manually disconnected to fix that.

This could help with building triangle adjacency data: Building triangle adjacency data

One note about data though - it should help performance if you treat the navigation mesh as any other - array of vertices, array of indices (triangles). The typical way is to create a graph and that's just going to slow things down in terms of memory allocations and cache.

As for pathfinding, there's no need to split anything - when you've built a path out of triangles, you also have the edges that connect the triangles. Due to the property of triangles (and convex polygons in general) that every ray that hits a polygon is going to hit it exactly twice (entry and exit points), any point on the edge is going to keep the path inside all visited triangles.

To optimize the path, the method I've found is to iteratively project line between previous/next points on the line of the current point, then limit it inside that line.

EDIT:

This is how I imagine line projection to work:

Intersect line formed by previous/next points with the straight line defined by crossed edge, then project this point onto the straight line, as well as both endpoints of the edge - from there you can limit the projection by the projections of edge endpoints, thus keeping the intersection point inside the edge. To retrieve the new point, subtract the old projection and add the new one.

The last part in pseudocode:

```
// p1 - edge point 1, p2 - edge point 2
// pp - projection of line between previous/next path points onto straight line formed by the edge
// new_pp - projection, limited to the edge
dir = normalize( p1 - p0 ); // edge axis
proj_p1 = dot( dir, p1 );
proj_p2 = dot( dir, p2 );
proj_pp = dot( dir, pp );
cproj = clamp( proj_pp, proj_p1, proj_p2 );
new_pp = pp + dir * ( cproj - proj_pp );

```

For the intersection test, look for any segment-plane intersection test. The segment is defined by previous/next path points. A plane can be defined by two cross products - first one between path segment and edge, second from the new vector and the edge - this is the plane normal. Any point on edge is a good plane reference point.

---
Tags: path-finding, navmesh
---


# Question
Title: Moving a character based on a list of Vector 3's
I have a client server scenario. On the server there is an AI character who chooses a random point on the map and pathfinds to it, when at that point it chooses a new point and pathfinds again etc. The path to each point is an array which I send to the client, then a character on the client goes to each point in the array, making it look as though it is in sync with the server's AI character. (I realise with Unet all I really need is a network identity script and network transform component but this is a means to an end using this method).

So when the server creates the array and sends its own AI character off on the path, this array is sent to the client, the client then puts it into a List. Then using this List the Clients character moves to each node smoothly looking just like the server. My problem is that sometimes it moves and others it sticks and I get an error

> "ArgumentOutOfRangeException: Argument is out of range. Parameter name: index"

My code is as follows:

Script that sends path and receives:

```
public class AccessingTargetPos : NetworkBehaviour {
public List<Vector3> receivedArrays = new List<Vector3>();

[ClientRpc]
void RpcPosFromServerToGoTo(Vector3 [] path)
{
    UnityEngine.Debug.Log ("Going to ... " + path);
    receivedArrays.AddRange (path);
}

public void PrintPath(Vector3 [] path)
{
    if (isServer)
    {
        UnityEngine.Debug.Log("Send Array ...");
        RpcPosFromServerToGoTo (path);
        UnityEngine.Debug.Log("Sent!!");

    }
}

}

```

And my code that moves the client character based on the List:

```
public class ClientAiMoveToPosArray : MonoBehaviour {

AccessingTargetPos accessingTargetPos;
public float speed = 1;
public Vector3 endPoint;
int index = 0;
// Use this for initialization
void Start ()
{
    accessingTargetPos = GameObject.Find ("A*").GetComponent<AccessingTargetPos> ();
}
// Update is called once per frame
void Update ()
{
    transform.position = Vector3.MoveTowards (transform.position, accessingTargetPos.receivedArrays [index], speed * Time.deltaTime);

    if(transform.position == accessingTargetPos.receivedArrays [index])
        {
            index++;
        }
}
}

```

I don't understand why I am getting this error and why at times my clients character sticks. I assume I am going wrong somewhere in my `ClientAiMoveToPosArray` script. Am I wrong in there somewhere?

**UPDATE**

The error occurs for 3 reasons:

1. At the beginning when the client has no point to move to i.e. I start the server then the array is generated, however the client hasn't connected yet. If the client connects when the AI is moving along a path it has to wait until a new path is generated before moving.
2. If the AI character on the server gets stuck in an unwalkable area.
3. If the client is moving exactly like the server AI character. The error is appears here because when the array is generated it has to be sent over to the client, resulting in a slight delay.

# Answer
Apologies for taking so long, but following the update included in the original question, the error occurs for 3 reasons:

1. At the beginning when the client has no point to move to i.e. I start the server then the array is generated, however the client hasn't connected yet. If the client connects when the AI is moving along a path it has to wait until a new path is generated before moving.
2. If the AI character on the server gets stuck in an unwalkable area.
3. If the client is moving exactly like the server AI character. The error is appears here because when the array is generated it has to be sent over to the client, resulting in a slight delay.
> 1 votes

---
Tags: c#, movement, unity, unity-networking
---


# Question
Title: Combining Many Small Colliders into Larger Ones
I am creating a game using a tile-map made of many thousands of grid squares. At the moment, each square has a square collider on it for checking collisions.

However, with many thousands of tiny blocks, checking them all for collisions is inefficient. If I had known the tilemap was going to look like this in advance, I could have just used 3 or 4 big colliders rather than thousands of tiny ones:

Is there some sort of standard algorithm for combining many small adjacent tiles into maximally large ones? If so, could someone describe it here, or point to literature on such algorithms?

Alternatively, maybe pre-processing the tile colliders in this way is completely the wrong approach. If so, what is the correct one to deal with the efficiency of an extremely large number of colliders?

# Answer
I found usefull this algoritm for love2d engine (lua language)

https://love2d.org/wiki/TileMerging

```
-- map_width and map_height are the dimensions of the map
-- is_wall_f checks if a tile is a wall

local rectangles = {} -- Each rectangle covers a grid of wall tiles

for x = 0, map_width - 1 do
    local start_y
    local end_y

    for y = 0, map_height - 1 do
        if is_wall_f(x, y) then
            if not start_y then
                start_y = y
            end
            end_y = y
        elseif start_y then
            local overlaps = {}
            for _, r in ipairs(rectangles) do
                if (r.end_x == x - 1)
                  and (start_y <= r.start_y)
                  and (end_y >= r.end_y) then
                    table.insert(overlaps, r)
                end
            end
            table.sort(
                overlaps,
                function (a, b)
                    return a.start_y < b.start_y
                end
            )

            for _, r in ipairs(overlaps) do
                if start_y < r.start_y then
                    local new_rect = {
                        start_x = x,
                        start_y = start_y,
                        end_x = x,
                        end_y = r.start_y - 1
                    }
                    table.insert(rectangles, new_rect)
                    start_y = r.start_y
                end

                if start_y == r.start_y then
                    r.end_x = r.end_x + 1

                    if end_y == r.end_y then
                        start_y = nil
                        end_y = nil
                    elseif end_y > r.end_y then
                        start_y = r.end_y + 1
                    end
                end
            end

            if start_y then
                local new_rect = {
                    start_x = x,
                    start_y = start_y,
                    end_x = x,
                    end_y = end_y
                }
                table.insert(rectangles, new_rect)

                start_y = nil
                end_y = nil
            end
        end
    end

    if start_y then
        local new_rect = {
            start_x = x,
            start_y = start_y,
            end_x = x,
            end_y = end_y
        }
        table.insert(rectangles, new_rect)

        start_y = nil
        end_y = nil
    end
end
Here's how the rectangles would be used for physics.
-- Use contents of rectangles to create physics bodies
-- phys_world is the world, wall_rects is the list of...
-- wall rectangles

for _, r in ipairs(rectangles) do
    local start_x = r.start_x * TILE_SIZE
    local start_y = r.start_y * TILE_SIZE
    local width = (r.end_x - r.start_x + 1) * TILE_SIZE
    local height = (r.end_y - r.start_y + 1) * TILE_SIZE

    local x = start_x + (width / 2)
    local y = start_y + (height / 2)

    local body = love.physics.newBody(phys_world, x, y, 0, 0)
    local shape = love.physics.newRectangleShape(body, 0, 0,
      width, height)

    shape:setFriction(0)

    table.insert(wall_rects, {body = body, shape = shape})
end

```

Here follow the love2d example on my current project. In red you can see my wall colliders.
> 5 votes

# Answer
If you are looking to create destructible terrain, the way I did this in Unity, is to only set colliders on the edge blocks of your world. So for example, this is what you would like to accomplish:

All those green blocks contain a collider, and the rest of them don't. That saves a ton on computations. If you destroy a block, you can activate the colliders on adjacent blocks pretty easily. Keep in mind that activating/deactivating a collider is costly and should be done sparingly.

So, the Tile resource looks like this:

It is a standard gameobject, but it is also poolable. Also notice that the box collider is set to be disabled by default. We would only activate if it is an edge tile.

If you are statically loading your world, there is no need to pool your tiles. You can just load them all in one shot, calculate their distance from the edge, and apply a collider if required.

If you are loading dynamically, it is best to use a tile pool. Here is an edited example of my refresh loop. It loads tiles based on the current camera view:

```
public void Refresh(Rect view)
{
    //Each Tile in the world uses 1 Unity Unit
    //Based on the passed in Rect, we calc the start and end X/Y values of the tiles presently on screen
    int startx = view.x < 0 ? (int)(view.x + (-view.x % (1)) - 1) : (int)(view.x - (view.x % (1)));
    int starty = view.y < 0 ? (int)(view.y + (-view.y % (1)) - 1) : (int)(view.y - (view.y % (1)));

    int endx = startx + (int)(view.width);
    int endy = starty - (int)(view.height);

    int width = endx - startx;
    int height = starty - endy;

    //Create a disposable hashset to store the tiles that are currently in view
    HashSet<Tile> InCurrentView = new HashSet<Tile>();

    //Loop through all the visible tiles
    for (int i = startx; i <= endx; i += 1)
    {
        for (int j = starty; j >= endy; j -= 1)
        {
            int x = i - startx;
            int y = starty - j;

            if (j > 0 && j < Height)
            {
                //Get Tile (I wrap my world, that is why I have this mod here)
                Tile tile = Blocks[Helper.mod(i, Width), j];

                //Add tile to the current view
                InCurrentView.Add(tile);

                //Load tile if needed
                if (!tile.Blank)
                {
                    if (!LoadedTiles.Contains(tile))
                    {
                        if (TilePool.AvailableCount > 0)
                        {
                            //Grab a tile from the pool
                            Pool<PoolableGameObject>.Node node = TilePool.Get();

                            //Disable the collider if we are not at the edge
                            if (tile.EdgeDistance != 1)
                                node.Item.GO.GetComponent<BoxCollider2D>().enabled = false;

                            //Update tile rendering details
                            node.Item.Set(tile, new Vector2(i, j), DirtSprites[tile.TextureID], tile.Collidable, tile.Blank);
                            tile.PoolableGameObject = node;
                            node.Item.Refresh(tile);

                            //Tile is now loaded, add to LoadedTiles hashset
                            LoadedTiles.Add(tile);

                            //if Tile is edge block, then we enable the collider
                            if (tile.Collidable && tile.EdgeDistance == 1)
                                node.Item.GO.GetComponent<BoxCollider2D>().enabled = true;
                        }
                    }
                }
            }
        }
    }

    //Get a list of tiles that are no longer in the view
    HashSet<Tile> ToRemove = new HashSet<Tile>();
    foreach (Tile tile in LoadedTiles)
    {
        if (!InCurrentView.Contains(tile))
        {
            ToRemove.Add(tile);
        }
    }

    //Return these tiles to the Pool
    //this would be the simplest form of cleanup -- Ideally you would do this based on the distance of the tile from the viewport
    foreach (Tile tile in ToRemove)
    {
        LoadedTiles.Remove(tile);
        tile.PoolableGameObject.Item.GO.GetComponent<BoxCollider2D>().enabled = false;
        tile.PoolableGameObject.Item.GO.transform.position = new Vector2(Int32.MinValue, Int32.MinValue);
        TilePool.Return(tile.PoolableGameObject);
    }

    LastView = view;
}

```

Ideally, I'd write a much more detailed post, as there is quite a bit more going on behind the scenes. However, this may help you out. If there are questions feel free to ask or contact me.
> 4 votes

---
Tags: collision-detection, tiles, tilemap, efficiency
---


# Question
Title: How do I make my foreground tiles stand out more from the background?
*(the background implemented in the game)*

In the game that I work on, the background and the map tiles are pretty indistinguishable for new players, probably because they have similar colors and theme.

Are there any tips or tricks to make the background more like a background and be distinguishable from the map tiles?

The game has motion blur which kinda helps, when the player is running the background gets blurry therefore making it more distinguishable from the map tiles.
However, that is clearly not enough.

Any suggestions, tips or tricks will be greatly appreciated!

*(purely the background)*
***EDIT: Thank you for the suggestions and the ideas! here are some variations of this background that I came with.***

*(darker and way more blurry)*

*(dawn colors and some blur)*

*(one of the coolest things I've done + blur)*

*(one of the coolest things combined with dawn colors + blur)*

# Answer
Another option is to adjust your Hue, or colors in general, so that they are not the same color as your foreground elements.

Or you could try to give a bolder outline to the foreground elements to make them pop out at you.

However, in my opinion, this background is just way too busy and will be very difficult to differentiate from your foreground elements.
> 2 votes

# Answer
A good way to get an idea of how to make your foreground stand out from the background is to research similar games. If you look at games such as Sonic and Megaman, the backgrounds of the levels all appear either relatively darker or lighter than the foregrounds. In some cases, the background is blurred slightly, but this effect can have a negative impact on your game - what is the point in going through all the trouble to make a wonderful background if all you are going to do is blur it to make your foreground appear more prominent?

Additionally, in these games, the foregrounds are comprised of colors that compliment their respective backgrounds, and make them pop out. For example, if you had a prominently blue-colored background, one way to make your foreground pop out is to design it using warmer colors such as orange and yellow, because these colors complement the cooler blue colors. Castlevania did this exceptionally well:

Also note that the colors of tiles in the foreground are considerably brighter than those in the background, as can also be seen in Megaman X:

I should also note that in these games, depending on the setting, their backgrounds mostly share certain aspects in common. For example, in levels that are outside in the open world, the background is considerably smaller and the sky (blue, possibly with clouds) takes up most of the space.

Additionally, as Alexandre Vaillancourt pointed out, there may possibly be too much detail in your background. It's all about finding the right balance. If you look at similar games, their background sometimes have a high level of detail, and what makes the foreground pop out, is again, the correct balance of colors, shade and detail.
> 2 votes

# Answer
I am not expert at graphic design so when i want to make a game i usually test the graphic resource that i made in the game, if something is wrong I change it until I have decent graphic design

here what i propose : test a lot of background until you find the right one

**darker**

**blurr**

**with interference**

and you have a lot of other options and also it will be great if you add darker borders to your ground images.

hope this was helpful !
> 1 votes

---
Tags: tilemap, platformer, art, side-scroller
---


# Question
Title: What type of networking archtitecture does Unreal Engine 4 have?
I am working on online multiplayer FPS on UE 4 with up to 16 players. I am now at the making architecture model, stage.

I am doing research on possible server architecture model with respect for future scalability, bandwidth support etc. However I could not find any good information on how UE 4 networking work and what it's architecture. In order to know whether it will suit my needs and whether I will be able to modify it

# Answer
> 4 votes
I believe UE4 network architecture is roughly the same as in prior versions of Unreal Engine, perhaps with minor refinements, and goes back to the very first version of Unreal Engine.

This is a client-server system with very little difference between Unreal server and clients. They run the same game simulation code, potentially even the same executable with configuration deciding whether the instance will be client or server or both; however, a "headless" server, a game executable with rendering completely removed, is usually provided for convenience. It was customary in early games to have one player be the server and the rest clients; however, this became more difficult with NAT home router proliferation, and nowadays you may end up running the servers. Epic games certainly aren't going to run the server for you.

The clients and server run the same game logic. Some variables are designated as replicated, and will be sent by server to all clients, overriding every client's representation "in the past" based on the timestamp when the network packet was generated, and having the client predict the result forward to current frame. Not all state needs to be replicated, gameplay-irrelevant state is usually omitted if local prediction is good enough. There is also an RPC system that allows to call a function on an entity across all network nodes. Obviously the system must be two-way, all communication facilities that are present on the server must also be present on a client. However, to prevent the client from commanding everyone's state unfairly, there is an ownership system.

Having Unreal Engine 4 source at your disposal and a system which foresees rich and flexible network semantics, you can implement a different network architecture if you so desire. I can not assess the practical difficulty of doing so, however.

---
Tags: architecture, server, unreal, unreal-4
---


# Question
Title: Vuforia AR/VR sample with Google Cardboard SDK: I cannot switch from augmented reality to virtual reality
I have followed the Integrating Cardboard to the AR/VR Sample latest tutorial. I have configured the provided scene sample according to that tutorial. I have compiled it to Android without any problem.

The game load an AR scene with a yellow pointer in the center. If I understood well, **if a glaze at the ImageTargetStones GameObject, it will switch to VR. Unfortunately I cannot find that GameObject anywhere**. I only see the AR scene with nothing than the yellow pointer.

I don't find what I'm missing. Why is not that ImageTargetStones GameObject in the AR scene?

---

**UPDATE 1**

I think I want to use Vuforia for an uncommon use. I think that's a reason of a possible misunderstanding.

I don't want to use its image recognition possibilities. I want to switch between AR to VR when glazing to a button.

I have tried to duplicate the VRButton to move it to an independent place of the scene with no parent. I have checked its IsTrigger checkbox. I have added a PointerEnter EventTrigger that set Focused to true. I have added a PhysicsRaycaster to both AR Camera and MainCamera (child of CardboardMain-Head).

Nothing happens when I gaze at the button. I have to compile everytime I want to try it by the way. I did not manage to make it work in the editor.

---

**UPDATE 2**

I haven't been able to do it with vuforia yet. I have done it with WebCamTexture. Specifically, I have used the scripts of this answer: http://answers.unity3d.com/answers/687987/view.html . The result is not nice because the image from camera seems closer than it actually is (with Vuforia, there is not that problem)

# Answer
The AR Camera of the demo scene provided comes with a GazeRay GameObject. That GazeRay has a GazeRay Script Component. We have to increase the Size of View Triggers. Then we have to add the GameObject we want to trigger.

Notice the GameObject we want to trigger has a ViewTrigger Script Component we better take a look to.

Notice I don't understand why it is not working with the RayCast I mention in the UPDATE 1 of the question.

Screenshot:
> 0 votes

---
Tags: unity, virtual-reality, augmented-reality, vuforia
---


# Question
Title: ID3D11Device::CreateInputLayout: Encoded Signature size doesn't match specified size
I get `[ STATE_CREATION ERROR #161: CREATEINPUTLAYOUT_UNPARSEABLEINPUTSIGNATURE]` with the following code:

```
// Vertex data
struct VertexData {
    XMFLOAT3 v;
    XMFLOAT2 vt;
    XMFLOAT3 vn;
};

// ...

// Create the input layout vertex shader.
D3D11_INPUT_ELEMENT_DESC vertexLayoutDesc[] =
{
    { "V", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexData, v), D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "VT", 0, DXGI_FORMAT_R32G32_FLOAT, 0, offsetof(VertexData, vt), D3D11_INPUT_PER_VERTEX_DATA, 0 },
    { "VN", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, offsetof(VertexData, vn), D3D11_INPUT_PER_VERTEX_DATA, 0 }
};

HRESULT hr = g_d3dDevice->CreateInputLayout(vertexLayoutDesc, _countof(vertexLayoutDesc), geomVertexShaderBlob->GetBufferPointer(), geomPixelShaderBlob->GetBufferSize(), &g_d3dInputLayout);

```

And wannabe matching HLSL code:

```
struct Input
{
    float3 v : V;
    float2 vt : VT;
    float3 vn : VN;
};

struct Output
{
    float4 color : COLOR;
    float4 position : SV_POSITION;
};

Output main(Input input) {...}

```

I can't spot the mismatch and what exactly the error message is pointing to. Weird thing I have very similar input layout and shaders that work perfectly fine, but this one doesn't.

# Answer
Looks like this is the issue (buffer pointer mismatch - geom**Vertex**ShaderBlob vs geom**Pixel**ShaderBlob):

> `geomVertexShaderBlob->GetBufferPointer(), geomPixelShaderBlob->GetBufferSize()`
> 2 votes

---
Tags: directx11, hlsl, data-structure
---