title: Help with OnTriggerEntered + Canvas UI

text:
# Question
Title: Help with OnTriggerEntered + Canvas UI
This seems like it should be incredibly easy and I know there are other posts out there with a similar title, but I promise you I have looked at all of them. All I want is for my canvas that simply says "you win" to appear when I enter an invisible box collider that I have . My canvas is by default set to disabled.

```
public class YouWin : MonoBehaviour {
public Canvas myCanvas;

private void Start()
{
    myCanvas = GetComponent<Canvas>();

}

void OnTriggerEnter (Collision Collider)
{
    {
        myCanvas.gameObject.SetActive(true);
    }
}

```

This script seems incredibly simple and straightforward, but for whatever reason, when I enter my box, nothing at all happens. Why might this be? What am I missing?

As per an answer I also tried

```
public class YouWin : MonoBehaviour {
public GameObject canvas;

void OnTriggerEnter (Collider Collider)
{
    {
        canvas.gameObject.SetActive(true);
    }
}

```

But had no luck with this either. I've been tinkering to no avail, can you please give me some suggestions?

# Answer
> 1 votes
It's unclear what exactly is wrong, here are a few things can could be wrong:

* Since you are using `OnTriggerEnter()` make sure the object attached to this script, has a `Collider` set with `isTrigger` to `true`.
* I'm not sure why you would attach a `Canvas` to an object that seems to resemble an actual object (either 2D or 3D). Try making the object with the `Canvas` a separate object, linked with `public Canvas canvas;` (also suggested by another answer). The idea of the `Canvas` is that it draws its children, so there (usually) isn't a need to make an object both draw stuff on the screen **and** being a `Canvas`.
* Maybe `OnTriggerEnter()` activates as expected, but you just don't see anything because you only enable a `Canvas` element in it, which could theoretically draw nothing on top of the screen (depending how you set it up). Try replacing `myCanvas.gameObject.setActive(true);` with something like `Debug.Log("canvas enables itself now");`, when running the game, take a look in the console to see if this runs or not.
* Also make sure that at least one of your objects has a `RigidBody` attached (Thanks @DMGregory), otherwise collisions are not triggered. You can take a look here for a table explaining how Unity calculates collisions and triggers.

It might also be useful to share your hierarchy, I suspect there's something there that could be causing the problem.

# Answer
> 0 votes
Your problem lies in the `GetComponent` call I think. GetComponent only works when the thing you're getting is on the same game object as the script.

Instead of getting the canvas game object that way, make a public game object variable for the canvas and then drag and drop your canvas into that slot in the inspector.

Just like this:

```
public class YouWin : MonoBehaviour {
public GameObject canvas;

void OnTriggerEnter (Collider Collider)
{
    canvas.SetActive(true);
}

```

All you have to do now is drag the canvas object into the slot that opens up in the inspector.

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


title: Find grandchildren with specific tag

text:
# Question
Title: Find grandchildren with specific tag
I have an empty object that contains multiple children each containing their own child objects. I want to get a list of all the objects containing a specific tag but i don't know the depth of each child object. The following solution only returns the children that have the tag.

```
foreach (Transform child in city)
        {
            if (child.CompareTag("Zone"))
                buildings.Add(child);
        }

```

# Answer
> 3 votes
You could try something like this.

```
public List<GameObject> GetChildrenWithTag(GameObject obj)
{
    var childrenWithTag = new List<GameObject>();
    var allChildren = obj.GetComponentsInChildren<Transform>();
    foreach(var child in allChildren)
    {
        if(child.gameObject.CompareTag("Zone"))
        {
            childrenWithTag.Add(child.gameObject);
        }
    }
    return childrenWithTag;
}

```

I didn't test this code but I guess it works. You may also want to avoid to hard-code tags like you did with "Zone".

---
Tags: unity
---


# Question
Title: Why when I change some values of propertie in the inspector of my script it's highlightnig the text?
A simple script that attached to a GameObject in the Hierarchy:

First the variable in the editor in the inspector of the script Speed Change Wait was highlighted I mean it's much black painted then the rest.

Then when I changed or changing other variables values in the editor in the inspector they are also become more black painted. In the screenshot the Headers like Door Init or Door Moves should be in black and painted more then the rest. But now also the other variables like this. I can't figure out why.

For example Random Speed Range is not yet in highlighted black but once I will change it's value it will too.

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

public class GateControl : MonoBehaviour
{
    [Header("Door Init")]
    [Space(5)]

    public Transform door;

    [Header("Door Moves")]
    [Space(5)]

    public float doorMovingLength = 64f;

    [Header("Door Speed")]
    [Space(5)]

    public float constantDoorSpeed = 1f;
    public float currentDoorSpeed;

    [Header("Door Random")]
    [Space(5)]

    public bool randomDoorSpeed = false;
    public int speedChangeWait = 7;
    [Range(0.3f, 10)]
    public float randomSpeedRange;

    private Vector3 originalDoorPosition;
    private bool isRising = true;
    private float fraq = 0;
    private float timer = 0;

    // Use this for initialization
    void Start()
    {
        originalDoorPosition = door.position;
        StartCoroutine(DoorSpeedWaitForSeconds());
    }

    // Update is called once per frame
    void Update()
    {
        if (isRising)
            fraq += Time.deltaTime * currentDoorSpeed;
        else
            fraq -= Time.deltaTime * currentDoorSpeed;

        if (fraq >= 1)
            isRising = false;
        if (fraq <= 0)
            isRising = true;

        fraq = Mathf.Clamp(fraq, 0, 1);

        door.position = Vector3.Lerp(originalDoorPosition,
            new Vector3(originalDoorPosition.x, originalDoorPosition.y, doorMovingLength),
            fraq);
    }

    IEnumerator DoorSpeedWaitForSeconds()
    {
        timer = 0;

        while (true)
        {
            if (randomDoorSpeed == true && randomSpeedRange > 0.3f)
                currentDoorSpeed = Random.Range(0.3f, randomSpeedRange);

            if (!randomDoorSpeed)
                currentDoorSpeed = constantDoorSpeed;//reset back to original value

            while (timer < speedChangeWait) { timer += Time.deltaTime; yield return null; }
            timer = 0;
        }
    }

    #if UNITY_EDITOR // make OnValidate() only exist in Editor mode
    private void OnValidate()
    {
        timer = 0;
    }
    #endif
}

```

# Answer
> 3 votes
The hightlight indicates that the values are not the default values of the prefab but are specific to this instance. If you want to apply these changes to your prefab you can press "Appply" on the top of the editor and the values will no longer be highlighted since they became the default value of the prefab.

You can read this sentence in the Prefab Documentation :

> To make it clear when a property has been overridden, it is shown in the inspector with its name label in boldface.

# Answer
> 0 votes
The highlight indicates that that value is not at it's default value.

As I recall there's a right click option to reset it to the default value. It is purely there as a visual aid.

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


# Question
Title: How can I tile Perlin noise to more accurately represent a world map?
I'm currently working on my game. I would like to generate the world map with Perlin noise, and wrap it just like a real world map. I've found a algorithm to create a map wrapped along X and Y axis:

Procedurally Generating Wrapping World Maps

The problem is that this map have no linear equator and poles. If you cross the north pole, you will end up in the south. A realistic map should be like this:

So when you cross the north pole you end up at the opposite longitude. So when you get an arial view of this flat map, you get something like this:

The problem is that I don't know how to generate a perlin noise that repeat itself like this. In the website I linked, they use a 4D Perlin noise. But I still can't figure out how to use it for my case. Here is the code used in the link:

```
for (var x = 0; x < Width; x++) {
    for (var y = 0; y < Height; y++) {

        // Noise range
        float x1 = 0, x2 = 2;
        float y1 = 0, y2 = 2;
        float dx = x2 - x1;
        float dy = y2 - y1;

        // Sample noise at smaller intervals
        float s = x / (float)Width;
        float t = y / (float)Height;

        // Calculate our 4D coordinates
        float nx = x1 + Mathf.Cos (s*2*Mathf.PI) * dx/(2*Mathf.PI);
        float ny = y1 + Mathf.Cos (t*2*Mathf.PI) * dy/(2*Mathf.PI);
        float nz = x1 + Mathf.Sin (s*2*Mathf.PI) * dx/(2*Mathf.PI);
        float nw = y1 + Mathf.Sin (t*2*Mathf.PI) * dy/(2*Mathf.PI);

        float heightValue = (float)HeightMap.Get (nx, ny, nz, nw);

        mapData.Data[x,y] = heightValue;
    }
}

```

I'm currently using spherical coordinates, but the map is distorded at the poles.

# Answer
For this particular mapping, I'd stick to 2D Perlin noise.

To recap, 2D Perlin noise works by...

* dividing space into square cells, and examining the one cell our sample point falls inside
* picking a pseudorandom gradient vector at each corner of the square cell
(in a consistent way, so repeated samples in the same vicinity all agree)
* interpolating the four gradient vectors according to our sample position inside the cell

So, to get clean tiling, we need to:

1. ensure our sampling grid is aligned with the edges of the map (ie. there's an integer number of sampling grid cells across the map vertically & horizontally)
2. choose our gradient vectors in a way that's consistent across tile seams

After that, we can let the rest of Perlin noise run as normal. If the inputs are consistent across the tile seams, then the outputs will be consistent too.

To get consistent gradients across tile seams, we'll insert a remapping step into the gradient selection process, so each corner of our grid gets mapped to a canonical point that matches its counterpart on the other side of the seam. (Note that for the particular mapping scheme shown in the question, we also need to vertically flip the gradients shown in red)

Here I'm choosing to treat the left half of the map as canonical, and remap the top-right, right, and bottom-right edges to match their counterparts on the left.

You can see the effect in this animation that shows a single octave of Perlin noise, cycling between the normal gradient lookup (shows seams at the edges), our corrected wrapping (seamless), and the difference between the two (highlights where the gradients change along the right edge of the tile)

So, how do we do that?

Let's say we're given as input a 2D floating point vector, `sample`, such that `0 <= sample.x <= 2 * height`, and `0 <= sample.y <= height`, where `height` is the vertical sampling frequency of the current octave of noise (how many grid cells we want between the top & bottom edges of the map)

Our closest four corners are then initially (clockwise from the bottom-left):

```
a = (floor(sampleX), floor(sampleY))
b = (     a.x      ,    a.y + 1    )
c = (   a.x + 1    ,    a.y + 1    )
d = (   a.x + 1    ,      a.y      )

```

An ordinary Perlin Noise would then look something like this:

```
// Get our sample position within the cell, in the range 0 <= x,y < 1.
Vector2 fraction = sample - a;

// Look up our four pseudo-random vectors for the surrounding corners.
Vector2 gradientA = GetPerlinGradient(a);
Vector2 gradientB = GetPerlinGradient(b);
Vector2 gradientC = GetPerlinGradient(c);
Vector2 gradientD = GetPerlinGradient(d);

// Compute an intensity according to each corner.
float dotA = Dot(gradientA, fraction);
float dotB = Dot(gradientB, fraction - Vector2(0, 1));
float dotC = Dot(gradientC, fraction - Vector2(1, 1));
float dotD = Dot(gradientD, fraction - Vector2(1, 0));

// Interpolate the four intensities according to our sample position:
float bottom = Interpolate(  dotA, dotD, sample.x);
float top    = Interpolate(  dotB, dotC, sample.x);
float middle = Interpolate(bottom,  top, sample.y);

return middle;

```

We're going to modify this by sticking a wrapping "adapter" function in place of the `GetPerlinGradient(a/b/c/d)` calls above:

```
Vector2 GetWrappedPerlinGradient(int2 corner, int height) {

    // We'll use this to track whether we're sampling a mirrored point.
    float flipY = 1f;

    if(corner.x >= height) {
        if(corner.x == 2 * height) {
             corner.x = 0;
        } else if(corner.y == 0 || corner.y == height) {
             corner.x -= height;
             flipY = -1f;
        }
    }

    Vector2 gradient = GetPerlinGradient(corner);
    // If you like, you can apply an offset here GetPerlinGradient(corner + seed);
    // to generate different maps from the same hash function.

    gradient.y *= flipY;
    return gradient;
}

```

Now samples on both sides of the seam will use gradients that are compatible at the edges, resulting in the mapping you're looking for.

Here's an example of terrain generated world map with seamless tiling using this method:
> 13 votes

# Answer
You have conflicting goals. A flat 2D map that wraps along the X & Y axis doesn't map to a sphere, it maps to a torus (donut). To visualize this, imagine you have a sheet of elastic. First, bend it into a horizontal tube. This corresponds to having the Y axis wrap. Next bend it so that the open ends of the tube meet. This corresponds to having the X axis wrap. The result looks something like this:

(taken from: Robert Hanson - Asteroids: What is the shape of your Universe?)

To come at the problem for the other side, consider a mercator projection map of the earth:

As you state, in real life you don't walk off the south pole onto the north pole. But if you use the actual map of the earth & assume X/Y wrapping, that's what would happen. The actual problem is that the topology of a sphere does not have X/Y wrapping. The idea of X/Y wrapping is a convenient fiction perpetuated by video games. I suspect many games use it because it is both easy both for developers to program & for players to understand.

Thus, you can have seamless X/Y wrapping or you can have something that maps to a sphere, but you cannot have both at the same time.

Incidentally, while an X/Y wrapped map doesn't provide north & south poles (because it can't represent a sphere), it does create a north & south equator! By selecting two horizontal lines that are half the image height apart, we can orient them such that one will paint a ring on the north side of the torus & the other will paint a ring on the south. For instance, let's select the top/bottom edge for one line & place the other in the middle:

Then we end up with the following in 3D:

Note: there's a small error in my 3d renderings - the texture is duplicated twice horizontally due to the way my mesh was generated.
> 7 votes

# Answer
If you just need a repeating background, but don't need it *all* to fit in the viewport, this will work quite well.

If you consider a rectangle projected on to the surface of a sphere, you can get a pretty neat repeating background.

(Images borrowed from CambridgeInColour.com)

Take a look at this:

and this from math.stackexchange.com (https://math.stackexchange.com/questions/262809/spherical-projection)

Imagine that there is a large sphere floating behind your background. For each pixel in your background image, project a ray onto that imaginary sphere. (Simple ray/sphere intersection, documented all over the web.) At that intersection of the ray and the sphere, sample 3D Perlin space.

Now, here's the trick (if there is one): As your player moves to the right, rotate the sphere (really, rotating the intersection point about the center of the sphere) before sampling.

As the sphere rotates, the effect is the same as if the projected quad is moving across the surface of the sphere, and thus through Perlin space. Since the rectangle will eventually wrap around the sphere in whatever direction you're moving, the background will also repeat.

The larger the rectangle you use, the more distortion / fisheye you'll see near the edges of the viewport.

You could also do this using the Mercator projection method discussed in the comments above rather than generating it dynamically. The key to a good, hardly-distorted output, though, is the projection, and using only a relatively small portion of the sphere at a given time.
> 2 votes

---
Tags: c++, procedural-generation, perlin-noise
---


# Question
Title: Using PyOpenGL, can I rotate raw data rather than the current matrix?
I'm trying to create a sort of PyOpenGL renderer for the Bullet physics engine, and at the moment I'm rotating my basic cubes with math in Python. However, if I do the math in Python that's going to take more time than doing the math with OpenGL.

OpenGL has the ability to rotate a matrix using glRotatef(), but it only rotates the "current matrix". I'm not really interested in convoluting my render loop with an individual check for each object's rotation and position if I don't have to.

So my question is, is there a way I can, for example, load a matrix of points into OpenGL, rotate this matrix and then read it back and give it to my render loop? Or should I instead look for an alternative 3D math library? (Or for that matter, is running the code in python really all that laggy?)

# Answer
> 1 votes
First of all, it is good that you appear to be on the right track with using VBOs! In general, it is a good idea when working with the GPU to pass as much data to the GPU at once as is possible. This means minimizing the number of draw calls (i.e. send a whole bunch of cubes in a single draw call rather than drawing one cube at a time with `glDrawArrays` or worse, `glVertex`).

Let's say that the vertices, texture coordinates, normals, etc are all in a massive interleaved VBO or set of VBOs (e.g. one for vertices, one for normals, and so on). How do you rotate these cubes? One approach would be to pass uniforms in for your model, view, and projection matrices for each cube and draw each cube in your VBO with a single glDrawArrays call. This, however, would be exceedingly slow, and it would be better if we could tell the GPU to draw all of our cubes in one go. While there are other techniques to consider in OpenGL such as instancing, one approach could be to pass in transformation matrices as an additional attribute per-vertex. These matrices could either be calculated on the CPU side (possible, but potentially slow, especially in python) or on the GPU side (fast and what I would generally recommend, but possibly wasteful of GPU resources to calculate these transformations repeatedly for each vertex). You can also consider transforming the vertices on the CPU side every frame and passing the transformed vertices to your shader instead, but this could once again be a bottleneck in python.

In addition to the concerns on the OpenGL/GPU side of things, there are also some unique challenges posed by using python. A useful blog post for me that points out some of these issues can be found here, but I will try to sum up some of the highlights.

* There is first the issue of Python's memory model. In python, everything, even primitives such as integers, are all bulky objects built from a basic `PyObject` struct rather than direct, native machine types. This can make accessing the data of the underlying objects slow as a result, with even apparently simple operations such as adding two numbers invoking lots of operations behind the scenes in the python interpreter. For fast math operations, this is not conducive to good performance, and there is generally little to gain from the safety features (such as avoiding overflow) that are offered from this additional layer.
* The issues of dealing with objects rather than primitives is worsened when you are working with lots of these objects (aka in many matrices and vectors). You mention in the comments that these matrices that you build are actually python lists. While these lists in python are generally contiguous in memory, they contain contiguous PyObjects representing floats rather than just the floats themselves. This can result in a loss of potential data locality. The result is that accessing each element in your matrices would be slower as well.
* Finally, the performance of loops and function calls is significantly slower in python than it is in say, C. Games generally have a soft realtime requirement for performance, meaning that we generally want them to run interactively at a smooth framerate. If you are targeting 60 fps, for example, this means that you only have about 16.67 milliseconds to execute everything your game needs to do to render a given frame. On my laptop, this amounts to having 100,000 function calls at the most every frame. This can be limiting, especially in tight loops at the core of a game engine. This is frustrating when compared to the overhead of C functions, which are an order of magnitude or two faster to run. This overhead is signficant even when the python calls wrap C calls to system libraries like OpenGL! When possible, these expensive loops should be moved out of python and into faster, typed, and compiled code. The general idea is that you should pass in a group of objects from python to some C function that does all of the hard work!

Hopefully this gives a good idea of some of the challenges that come with using python. I do believe that it should be possible to create great games in python and that scripting languages like python have their place, but there are many factors to consider regarding performance. The choice you make ultimately depends on your workload and what exactly you are rendering to your screen. Let me know if there is anything that I can clear up!

---
Tags: opengl, 3d, rendering, rotation, python
---


# Question
Title: Physics - How to calculate the next position of a ball rolling against a slope?
For a small C/C++ game project, I want to add some physics on a ball, to allow it to roll against the slopes of a 3d world, in the same way as the example visible in the image below:

However I have very few skills in physics, and I have some trouble to understand which physical laws should be applied, and how concepts like energy, force and acceleration should be used here. As a beginner, I imagined the situation as follow:

Where:

* N (in green) is the normal of the current polygon above the ball
* Fg (in red) is the gravitational force, which should be constant
* Ff (also in red) is the frictional force, which should be constant
* P (in blue) is the current ball position
* P' (also in blue) is the next point to calculate

I also wrote a dedicated function to calculate the physics on my ball, which is called every time a frame is about to be rendered. When this function is called, I know:

* The elapsed time
* The current ball position
* Which polygon is currently below the ball (from which I can extract the N normal shown above, and thus the slope) The constant forces (Fg and Ff shown above)

From these values I tried to calculate the next ball position (P' shown above) based on the physics law F = m * a

This gave the following code:

```
#define M_CSR_Gravitation 9.81f

typedef struct
{
    CSR_Vector3 m_AccumulatedForce;
    float       m_Mass;
} CSR_Body;

typedef struct
{
    CSR_Vector3 m_Position;
    CSR_Sphere  m_Geometry;
    CSR_Body    m_Body;
} CSR_Ball;

CSR_Ball g_Ball;

void csrPhysicsGravity(float mass, CSR_Vector3* pF)
{
    // the formula for the gravitation is F = m * g
    pF->m_X = 0.0f;
    pF->m_Y = mass * M_CSR_Gravitation;
    pF->m_Z = 0.0f;
}

void ApplyPhysics(float elapsedTime, CSR_Plane groundPlane, const CSR_Vector3& frictionForce)
{
    float       dirAngleX;
    float       dirAngleZ;
    float       velocityAngle;
    CSR_Vector3 planeNormal;
    CSR_Vector3 gravity;
    CSR_Vector3 xDir;
    CSR_Vector3 zDir;
    CSR_Vector3 up;
    CSR_Vector3 dropForce;
    CSR_Vector3 motionForce;
    CSR_Vector3 acceleration;
    CSR_Vector3 prevCenter;

    planeNormal.m_X = groundPlane.m_A;
    planeNormal.m_Y = groundPlane.m_B;
    planeNormal.m_Z = groundPlane.m_C;

    // calculate the gravity force applied on the ball
    csrPhysicsGravity(g_Ball.m_Body.m_Mass, &gravity);

    xDir.m_X = 1.0f;
    xDir.m_Y = 0.0f;
    xDir.m_Z = 0.0f;

    // calculate the angle to drift against the x axis
    csrVec3Dot(&xDir, &planeNormal, &dirAngleX);

    zDir.m_X = 0.0f;
    zDir.m_Y = 0.0f;
    zDir.m_Z = 1.0f;

    // calculate the angle to drift against the z axis
    csrVec3Dot(&zDir, &planeNormal, &dirAngleZ);

    up.m_X = 0.0f;
    up.m_Y = 1.0f;
    up.m_Z = 0.0f;

    // calculate the drift velocity (the steeper is the slope, the higher is the fall speed)
    csrVec3Dot(&up, &planeNormal, &velocityAngle);

    // calculate the drift offsets to apply on the next frame
    dropForce.m_X = dirAngleX * velocityAngle * -gravity.m_Y;
    dropForce.m_Y = 0.0f;
    dropForce.m_Z = dirAngleZ * velocityAngle * -gravity.m_Y;

    motionForce.m_X = g_Ball.m_Body.m_AccumulatedForce.m_X + dropForce.m_X - frictionForce.m_X;
    motionForce.m_Y = g_Ball.m_Body.m_AccumulatedForce.m_Y + dropForce.m_Y - frictionForce.m_Y;
    motionForce.m_Z = g_Ball.m_Body.m_AccumulatedForce.m_Z + dropForce.m_Z - frictionForce.m_Z;

    g_Ball.m_Body.m_AccumulatedForce = motionForce;

    acceleration.m_X = (motionForce.m_X / g_Ball.m_Body.m_Mass) * elapsedTime;
    acceleration.m_Y = (motionForce.m_Y / g_Ball.m_Body.m_Mass) * elapsedTime;
    acceleration.m_Z = (motionForce.m_Z / g_Ball.m_Body.m_Mass) * elapsedTime;

    prevCenter = g_Ball.m_Geometry.m_Center;

    g_Ball.m_Geometry.m_Center.m_X += -acceleration.m_X * elapsedTime;
    g_Ball.m_Geometry.m_Center.m_Y += -acceleration.m_Y * elapsedTime;
    g_Ball.m_Geometry.m_Center.m_Z += -acceleration.m_Z * elapsedTime;
}

```

It works very roughly. The ball actually rolls down the slope, but never stops. And if I try to throw the ball from the bottom of the slope, it accelerates instead of curbing.

Obviously something is pretty wrong, but what? As I say above, I'm not an expert in physics and I think I tend to confuse notions such acceleration, force and energy. However I tried to resolve this system by myself, without success.

So I would be thankful if somebody can explain to me:

* Which concepts of physics are involved to resolve the above mentioned system
* How should I correct my code to reach the above described objective (of course as long as the code does not have to be rewritten entirely)
* And/Or an example of a such algorithm, even if written in pseudo-code or in another programming language

**IMPORTANT NOTE** I know that there are many physics engines, commercial or open-source, like e.g. Bullet, Box2d or Havok, which I may use to resolve the above issue. **THIS IS NOT MY OBJECTIVE**, I wan't to use them, at least for now. **I WANT TO LEARN AND UNDERSTAND** how to resolve this issue before using such engines. And I think that the proposed problem is simple enough to serve for this purpose.

# Answer
Finally I found an acceptable solution, based on the following article: The Physics of Golf (search the "Rolling on inclined planes " part)

I'm aware that it is anything but perfect, but it works sufficiently well in my small simulation. Thanks to all which taken a time to post an answer, this really helped me.

Here is my solution:

```
//---------------------------------------------------------------------------
void csrPhysicsGravity(float mass, float* pF)
{
    // the formula for the gravitation is F = m * g
    *pF = mass * M_CSR_Gravitation;
}
//---------------------------------------------------------------------------
void csrPhysicsRoll(const CSR_Vector3* pSlopeDir,
                          float        mass,
                          float        friction,
                          float        elapsedTime,
                          CSR_Vector3* pVelocity)
{
    float       gravity;
    float       thetaX;
    float       thetaZ;
    float       ffx;
    float       ffz;
    CSR_Vector3 xDir;
    CSR_Vector3 zDir;
    CSR_Vector3 acceleration;

    // calculate the gravity force to apply to the body
    csrPhysicsGravity(mass, &gravity);

    xDir.m_X = 1.0f;
    xDir.m_Y = 0.0f;
    xDir.m_Z = 0.0f;

    // calculate the slope angle on the x axis
    csrVec3Dot(&xDir, pSlopeDir, &thetaX);

    zDir.m_X = 0.0f;
    zDir.m_Y = 0.0f;
    zDir.m_Z = 1.0f;

    // calculate the slope angle on the z axis
    csrVec3Dot(&zDir, pSlopeDir, &thetaZ);

    // the angles should always be positive
    thetaX = fabs(thetaX);
    thetaZ = fabs(thetaZ);

    // calculate the friction force to apply to the body (using the formula a = dv / dt)
    if (elapsedTime)
    {
        ffx = (pVelocity->m_X / (elapsedTime * 1.0f)) * friction;
        ffz = (pVelocity->m_Z / (elapsedTime * 1.0f)) * friction;
    }
    else
    {
        ffx = 0.0f;
        ffz = 0.0f;
    }

    // calculate the body acceleration (using the formula a = ((m * g * sin(theta)) - Ff) / m)
    acceleration.m_X = ((gravity * thetaX) - ffx) / mass;
    acceleration.m_Z = ((gravity * thetaZ) - ffz) / mass;

    // calculate the final body velocity (using the formula v = v + (a * dt))
    pVelocity->m_X += (acceleration.m_X * elapsedTime);
    pVelocity->m_Z += (acceleration.m_Z * elapsedTime);
}
//---------------------------------------------------------------------------

```
> 1 votes

---
Tags: c++, physics, algorithm, physics-engine
---


# Question
Title: Calculating displacement in physics simulation
Something's been bugging me and I haven't been able to figure this out.

In a simply physics simulation, where you'd calculate a net force acting on a body every frame, calculate the acceleration that frame and from that the velocity and then distance travelled. (like this):

`a = F(given)/m` `v = a*dt` `s = v*dt`

Why is it not `s=0.5*vfinal*dt` (for constant acceleration), in other words, why is not customary to assume that the speed changes linearly during the timeframe dt instead of assuming that the velocity is constant during the frame.

# Answer
I was working through some formulas with this recently, and it turns out that using this approximation still gives a physically-correct trajectory, *for a slightly different initial velocity*.

ie. We'd expect a body starting at position \\$\vec p\_0\\$ with initial velocity \\$\vec v\_0\\$ under constant acceleration \\$\vec a\\$ (eg. due to gravity) to follow the parabola...

$$\vec p(t) = \vec p\_0 + \vec v\_0 \cdot t + \frac {\vec a} 2 \cdot t^2$$

But using the symplectic Euler integration with a fixed timestep \\$\Delta t\\$ in eg. Box2D, we instead see the parabola...

$$\vec p(t) = \vec p\_0 + (\vec v\_0 + \frac {\vec a} 2 \Delta t) \cdot t + \frac {\vec a} 2 \cdot t^2$$

This is still a physically-plausible trajectory (ie. given the motion observed on frame 1 & 2, all subsequent frames correctly match that observation), just with a slightly different boundary condition. And the error shrinks with smaller timesteps. The trick is that only someone with access to the "true" under-the-hood value of \\$v\_0\\$ could tell the difference. Any other observer would simply conclude that the velocity at the start was different, and the rest of the motion proceeds correctly from there.

Given that the initial velocities are usually either:

* **fully controlled by the game developer** (eg. specifying a jump impulse or launch velocity of a projectile), it's trivial for the developer to subtract a half-timestep of acceleration from the input up front to get back on the intended curve, without complicating the integrator.
* **extremely approximate *anyway*** (eg. the bounce resulting from a collision resolved with discrete overlap detection & restitution along the shortest penetration, rather than true continuous material simulation)

In practice, a realtime physics engine sweeps all kinds of things under the rug, like the precise moment within the frame when an impulse was applied (if it came near the start of the interval, then using the average velocity might make your simulation *less* accurate, not more) so it's not necessarily in the business of "true reproduction," just "plausible simulation"

...so the designers of these physics engines may have felt that this small approximation of the initial conditions (only half a timestep's worth of error) was reasonably harmless, in the contexts in which these engines tend to do their work.

Granted, this decision may have been made back in a day when processors were less powerful, and the simplification of an extra vector multiply & add out of the inner loop of the physics engine was significant. That might well not be the bottleneck today, but established physics engines could be wary to change the core integrator, for fear of breaking software, shared assets, and libraries that depend on the old behaviour.

If you're interested in experimenting with using the average velocity over the frame, instead of treating all acceleration as occurring at the beginning, it's worth a try. It's not physically wrong, but you might or might not find much benefit in terms of the visual plausibility of the simulation that results.
> 0 votes

---
Tags: physics
---


# Question
Title: Player stats include additional attribute
I am currently running a role-playing game called DNDBBS and would like to know: If there is stats for Strength, Intelligence, Wisdom, Dexterity, Constitution, Piety, should there be one for Charisma? Is this standard DND?

Edited: 07/31/2018 11:00:00 CST:

The DNDBBS is a Modem (POTS) oriented multi-node text based Adventure game. It can be found on google or http://www.filegate.net/pdnbasic/

Edited: 08/03/2018 21:25:00 CST:

I decided to also add Beauty and Glamour for Lady class.

# Answer
> 1 votes
> Is this standard DnD?

The standard DnD abilitiy scores are:

> * Strength, measuring physical power
> * Dexterity, measuring agility
> * Constitution, measuring endurance
> * Intelligence, measuring reasoning and memory
> * Wisdom, measuring Perception and Insight
> * Charisma, measuring force of personality

So Charisma is standard DnD, Piety is not. But that does not necessarily mean that this set of attributes is also ideal for reaching the design goals of *your* game (or for those of DnD, for that matter).

> Should I have Charisma?

When it comes to selecting and balancing character attributes in a role-playing game, you need to consider the following things:

* How often do situations occur where a specific attribute is used and how important is the outcome of these situations? You can place charisma-checks at every corner, or you can just have two or three in your entire game. They might be optional or unavoidable. Failing those checks can have major, minor or no consequences. If you want to make sure that all attributes are equally balanced, then you should try to have roughly the same amount of spotlight for every attribute. Note that this is often more influenced by the content of your game than by your game mechanics. But the more game mechanics make use of an attribute, the more opportunities you get to write situations where the attribute decides the outcome.
* What are the consequences of having a *very low* value in that one attribute and how do these compare to others? Would a 1 Charisma character be completely unplayable? How about 1 Strength? 1 Constitution? Try to make sure that each of these extreme character builds would be either equally crippled or equally viable.
* What are the consequences of having a *very high* value in that one attribute and how do these compare to others? Can a Charisma-focused character build overcome almost every challenge in the game? Or are there situations where it doesn't help at all? How does this situation compare to builds focused on other attributes? Avoid having the "one attribute to rule them all" which is clearly more useful than all others.
* How interesting are the playstyles of characters focusing on different attributes? For example, many RPG systems put a lot of focus on making their combat mechanics as deep and interesting as possible, while the game mechanics for non-combat situations are often rather shallow. Yes, there are of course many notable exceptions, but the majority of RPGs go into this direction. That means that players who focus on those attributes which are useful in combat have a far more interesting game experience than those who focus on non-combat attributes.

There are two ways to solve this problem. One is to get creative and come up with some non-combat game mechanics which are just as interesting as the combat mechanics. Another is to make sure that every attribute is relevant for combat. DnD integrates Charisma into its combat mechanics by making it relevant for the spellcasting abilities of certain classes and for saving throws against certain effects. But the DnD solution for this problem is still rather lackluster, because only a few classes need Charisma for spellcasting and Charisma saving throws are among the more obscure ones.

---
Tags: game-design
---


# Question
Title: What is it called when you combine textures for an object
I am trying to gain a better understanding for modeling and texturing for Unreal 4 and Blender. Now my question is: What is the process/result called when packing textures into one image as shown below?

# Answer
Atlas-packing.

When you take several textures from one or different models and pack them into one big atlas image.

(image from http://baddabigboom.com/2010/04/texture-atlases-part-2-making-them/)

Packing is usually performed by bin-packing algorithm.
> 3 votes

---
Tags: textures, terminology
---


# Question
Title: How to debug fatal signal 11 code 2 in UnityMain?
i have searched for the

> fatal signal caused by Render or GxDriver, FlashMuller in unity forum says it's google play

the error:

```
08-03 14:59:47.503 32020-32092/? A/libc: Fatal signal 11 (SIGSEGV), code 2, fault addr 0xcbe8dffc in tid 32092 (UnityMain), pid 32020 (com.tuo3.alive)
08-03 14:59:47.533 32121-32121/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
    Build fingerprint: 'OnePlus/OnePlus5T/OnePlus5T:8.1.0/OPM1.171019.011/1807181208:user/release-keys'
    Revision: '0'
    ABI: 'arm'
    pid: 32020, tid: 32092, name: UnityMain  >>> com.tuo3.alive <<<
08-03 14:59:47.544 32121-32121/? A/DEBUG: backtrace:
        #00 pc 000575d0  /system/lib/libc.so (je_arena_tcache_fill_small+71)
        #01 pc 00077919  /system/lib/libc.so (je_tcache_alloc_small_hard+16)
        #02 pc 00058fc7  /system/lib/libc.so (je_arena_palloc+1650)
        #03 pc 00069bd1  /system/lib/libc.so (imemalign+1164)
        #04 pc 0006d373  /system/lib/libc.so (je_memalign+26)
        #05 pc 001d6f18  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (UnityDefaultAllocator<LowLevelAllocator>::Allocate(unsigned int, int)+24)
        #06 pc 001da888  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (MemoryManager::Allocate(unsigned int, unsigned int, MemLabelId const&, AllocateOptions, char const*, int)+852)
        #07 pc 001da254  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (malloc_internal(unsigned int, unsigned int, MemLabelId const&, AllocateOptions, char const*, int)+128)
        #08 pc 00193bc8  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (core::StringStorageDefault<char>::assign(char const*, unsigned int)+180)
        #09 pc 00a350bc  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (__gnu_cxx::hashtable<std::pair<core::basic_string<char, core::StringStorageDefault<char>> const, ZipCentralDirectory::PathDescriptor>, core::basic_string<char, core::StringStorageDefault<char>>, __gnu_cxx::hash<core::basic_string<char, core::StringStorageDefault<char>>>, std::_Select1st<__gnu_cxx::hash>, std::equal_to<core::basic_string<char, core::StringStorageDefault<char>>>, std::allocator, <ZipCentralDirectory::
        #10 pc 00a34adc  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (_ZZN19ZipCentralDirectory20readCentralDirectoryEvEN3$_08__invokeERK15FileSystemEntryR12FileAccessorPKcRKN3zip4CDFDEPv+508)
        #11 pc 00a38160  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (zip::CentralDirectory::Enumerate(bool (*)(FileSystemEntry const&, FileAccessor&, char const*, zip::CDFD const&, void*), void*)+804)
        #12 pc 00a348d0  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (ZipCentralDirectory::readCentralDirectory()+20)
        #13 pc 00a26630  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (apkAddCentralDirectory+84)
        #14 pc 00a19074  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (Mount(char const*)+84)
        #15 pc 00a090dc  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (UnityInitApplication()+216)
        #16 pc 00a0a660  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (UnityPlayerLoop()+264)
        #17 pc 00a0cc68  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/lib/arm/libunity.so (nativeRender(_JNIEnv*, _jobject*)+228)
        #18 pc 000114cb  /data/app/com.tuo3.alive-VZWALBY70nH_dSDIQa_rKA==/oat/arm/base.odex (offset 0x10000)

[More discussion][2]

```

# Answer
I put too much files in `StreammingAssets` which lead to apk contains 2w+ files, then crash.

More debug detail
> 0 votes

---
Tags: unity, android
---


# Question
Title: Can I pass RaycastHit2D with a UnityEvent?
How do I target only the gameObject hit by my Raycast? Do I need to pass in the RaycastHit2D to a custom Unity Event?

I'm shooting a raycast, if it hits a valid target it fires off a UnityEvent to deduct health. My code is currently removing health from all "Enemy" prefabs within the scene even if they aren't being hit by the raycast.

```
public GameEvent OnDamaged;

public void ConfirmHit()
    {
        var target = Physics2D.Raycast(transform.position, Vector3.right * damageRange, damageRange, layermask);

if (!target) return;

        OnDamaged.Raise();
    }

```

if a target is hit by the raycast it will trigger the OnDamaged Event. The Event Triggers a simple function to decrease health.

```
public void DecreaseHealth(float amount)
{
    currentHealth -= amount;
}

```

# Answer
> 2 votes
To answer the surface question "Can I pass a \[value of some type\] with a UnityEvent" the answer is **yes**, by inheriting from the generic UnityEvent

```
[System.Serializable]
public class RaycastHit2DEvent : UnityEvent<RaycastHit2D> {
}

public class RaycastBroadcaster : MonoBehaviour {

    public RaycastHit2DEvent OnHit;

    ...
}

```

You can send up to four arguments of varying types this way.

---

However, I would not recommend using this to filter your "take damage" message. That scales as O(n) for the number of damageable entities in your scene, compared to O(1) for sending the message directly to the one you hit.

You can still use an event to alert systems that care about damage happening *somewhere/anywhere* (eg. combat flashing in your minimap, an announcer system, or an AI combat director) - as you're likely to have fewer of those to scan through and fewer false positives to reject, since scripts don't have to subscribe to the firehose just to get damage directed at themselves.

For the separate message of "I am trying to do damage to *you* specifically," I'd recommend using `GetComponent` methods as Joza100 describes.

If you're concerned about coupling, you can implement this via an interface. That way the script dealing the damage doesn't need to know every concrete variety of damage reaction script, it just needs to know "some scripts care about taking damage" - the same knowledge it needs to fire an OnDamage event anyway.

```
public interface IDamageTaker {
    void TakeDamage(
        float damage,
        DamageType type,
        Vector2 hitPosition,
        GameObject source);
}

```

Your concrete `Health` or `DamageTrigger` components can then implement this interface to do the corresponding thing (decrementing a health pool / dying, firing their own local aggro event for their AI to respond to, triggering a scripted destruction or puzzle sequence, etc.)

In your damage dealer script, you'd call it a bit like this:

```
 var hit = Physics2D.Raycast(
             transform.position,
             Vector3.right * damageRange,
             damageRange,
             layermask);

 if(!hit)
     return;

 var damageTaker = hit.transform.GetComponent<IDamageTaker>();

 // No need to broadcast any event if we hit something non-damageable.
 if(damageTaker == null)
     return;

 // Notify the thing we hit so it can process its damage reactions.
 // This could even return a value to say "nuh-uh, I'm invulnerable" or such.
 damageTaker.TakeDamage(damage, damageType, hit.point, gameObject);

 // Notify any listeners who want to know about damage everywhere.
 OnDamageAnywhere.Raise(hit);

```

If your objects are complicated and have many different scripts on them that all want to individually react when the object takes damage, you can route this through an intermediary. Stick one component on the object that uses its TakeDamage method to fire an object-local "I personally have taken damage" event. Then all the scripts on that object can subscribe to their local damage event, rather than listening to everybody's when they only care about their own.

# Answer
> 1 votes
You simply can't use a GameEvent for that because you add all enemies to the event and that's why all their Healths decrease.

You can get the target as a GameObject.

Get the HealthComponent (or whichever component the health is stored in) by using the `getComponent<>()` method.

Instead of that being triggered in the event, trigger it here!

```
public void ConfirmHit()
{
    var target = Physics2D.Raycast(transform.position, Vector3.right * damageRange, damageRange, layermask);

    if (!target)
        return;

    HealthComponent hpComponent = target.gameObject.getComponent<HealthComponent>();

    hpComponent.DecreaseHealth (amount);
}

```

When I used HealthComponent, I meant the component where you put your health. Depends on you, but just retrieve that component where your health is.

---
Tags: unity
---


# Question
Title: How can I start the race from a checkpoint with GTA 5 Map Editor?
When I use the official Map Editor from GTA V then it seems that you are only able to test the Map from the Start Point all the time. This is very annoying when you build a hardcore difficult Map and you don´t want to start all the time again from the Start Point.

Is there a way to start the Race from as example Checkpoint #3 instead of always from the Start Point? I think there must be a way because I can´t imagine that hardcore difficult Map Builders always restart the Map from the Start Point..

Btw I can't ask the question at rockstar forum because you need to be 1 month online with your account before you can ask questions.

# Answer
It seems that you only can manually spawn at each checkpoint but only with your default vehicle! This means at transform races it will sadly not help you! Very uncomfortable at all..

In general this checkpoint test system isn´t build good.. However maybe rockstar will add some changes to this..
> 1 votes

---
Tags: maps, modding
---


# Question
Title: How to access an uniform array with a float as index in GLSL?
I'm trying to do basic multitexturing of terrain in OpenGL.

Im building the terrain with an image representing different elements (beach, water, jungle...) :

Im trying to map each color of this image with a texture in my game: green color means grassTexture (id 0), blue color means waterTexture (id 1), etc...

My fragment shader contains an uniform array containing all textures that I use (grass, water, ...) :

`// Terrain.frag
uniform sampler2D terrainTextures[50];`

For each vertex of the terrain, I pass a float in\_TextureId corresponding to a texture id :

```
// Terrain.vert
layout (location = 0) in vec3 in_Vertex;
layout (location = 1) in vec4 in_Color;
layout (location = 2) in vec3 in_Normal;
layout (location = 3) in vec2 in_TexCoord;
layout (location = 4) in float in_TextureId;

```

Then im trying to display the correct texture for a vertex with this textureId in the fragment shader :

`outputColor = texture(terrainTextures[int(textureId)], texCoord);`

With this line, I have this result :

If I modify the code of the fragment shader with the following code :

```
highp int tid = int(textureId);
if(tid == 2)
{
   outputColor = texture(terrainTextures[int(textureId)], texCoord);
}
else if(tid == 1)
{
   outputColor = texture(terrainTextures[int(textureId)], texCoord);
}
else outputColor = texture(terrainTextures[int(textureId)], texCoord);`

```

It works better :

I can't understand why it's working with this code, i'm doing exactly the same thing in the first example.

Maybe it's not the good way to access an uniform array ?

# Answer
> 3 votes
I'm not 100% sure exactly what the cause of the problem is, but I know the "right" way to do what you're trying to achieve. But I think the problem is that an array of samplers is only supposed to be indexed with a compile time constant. In your if-else version, the compiler is probably able to figure out that there's only one possible answer in each case and replaces it with a constant.

As for what to do instead:

The best way to choose between multiple 2D textures of the same size in a shader is using a texture array. They are loaded like 3D textures, and let you extremely efficiently choose between textures in the shader.

You'll use a sampler2DArray instead of a sampler2D, and you'll use a 3D texture co-ordinate instead of 2D -- the third dimension is the index of the texture you want to use.

In this talk Approaching Zero Driver Overhead, representatives from the major GPU vendors come together to talk about the fastest way to do things. Texture Arrays (or Array Textures) are just about the easiest thing on the list, and are super fast.

---
Tags: opengl, shaders, glsl, multitexturing
---


# Question
Title: How to express and verify euler rotation limits in Unity
I need to find a way to set min and max angles for each Euler component and check whether `transform.localEulerAngles` falls within those limits.

My current code looks like this:

```
class JointLimit : MonoBehaviour
{
    [SerializeField]
    [Range(-180f, 180f)]
    private float minX = -180f;
    [SerializeField]
    [Range(-180f, 180f)]
    private float maxX = 180f;
    [SerializeField]
    [Range(-180f, 180f)]
    private float minY = -180f;
    [SerializeField]
    [Range(-180f, 180f)]
    private float maxY = 180f;
    [SerializeField]
    [Range(-180f, 180f)]
    private float minZ = -180f;
    [SerializeField]
    [Range(-180f, 180f)]
    private float maxZ = 180f;

    public float Error
    {
        get
        {
            Vector3 localEuler = transform.localEulerAngles;
            Vector3 signedLocalEuler = new Vector3(Mathf.DeltaAngle(localEuler.x, 0), Mathf.DeltaAngle(localEuler.y, 0), Mathf.DeltaAngle(localEuler.z, 0));

            float error = 0;
            error += Mathf.Max(0, minX - signedLocalEuler.x);
            error += Mathf.Max(0, signedLocalEuler.x - maxX);
            error += Mathf.Max(0, minY - signedLocalEuler.y);
            error += Mathf.Max(0, signedLocalEuler.y - maxY);
            error += Mathf.Max(0, minZ - signedLocalEuler.z);
            error += Mathf.Max(0, signedLocalEuler.z - maxZ);
            return error;
        }
    }
}

```

This basically checks whether the Euler components fall within the specified range and sums the exceeding angles up to an error.

The problem is that Unity internally stores rotations as Quaternions and that there can be several euler representations for a single Quaternion, like Euler 123f, 17f, 235f and Euler 57f, 197f, 55f are the same thing.

Is there any way I can bring an Euler representation into some kind of normalized form that allows me to reliably check it against my limits?

# Answer
Euler angles aren't necessarily a good way of expressing limits over arbitrary ranges, as their behaviour close to zero is very different from their behaviour away from zero.

Below I've visualized the forward, right, and up vectors of an object rotated with Euler angles over various ranges.

Here yaw ∈ \[-50, 50\] and roll ∈ \[-10, 10\]. From left to right, I gradually alter the pitch range, from pitch ∈ \[-10, 10\] to pitch ∈ \[70, 90\]. You can see I haven't reduced the range of allowed angles anywhere, only shifted where it starts.

And yet, when we look at the range of orientations allowed in these ranges, we can see all three axis regions distort and change size & shape. The allowed range of right vectors flattens toward a line, the forward vectors collapse toward a triangle, and the up vectors spread out in a wider arc.

So limits specified in Euler angles are error prone. If the ranges of allowed rotation you actually want look like this, for example:

...then there might be no combination of Euler min/max angles that corresponds to this shape.

For narrow Euler angle ranges, we can ameliorate this a bit by choosing a neutral orientation that corresponds roughly to the middle of our range, and then measure our Euler angles as relative deviations from this. This will tend to keep our min & max close to and symmetric about zero, where Euler angles are most intuitive.

```
Vector3 GetEulerOffset(Quaternion rotation, Quaternion neutral) {
    var localDeviation = Quaternion.Inverse(neutral) * rotation;
    return localDeviation.eulerAngles
}

```

If you want to avoid the non-uniformity and cross-axis wraparound problems of Euler angles altogether, then it's usually better to try to express your limitation in terms of vectors. Let's say we have an elbow joint that's allowed to rotate -70 degrees inward and 2 degrees outward relative to its parent.

We can get its forward direction in the parent's space as:

```
Vector3 localForward = transform.localRotation * Vector3.forward;

```

And convert this to an angle in the xz plane with known range -180 to 180, regardless of what's happening on the remaining axis.

```
float angle = Mathf.Atan2(localForward.z, localForward.x) * Mathf.Rad2Deg;

bool inRange = angle > -70 && angle <= 2;

```
> 6 votes

# Answer
Maintain your own layer that operates on euler angles, and keeps current values of these stored every frame. Unity *derives* the quaternion form for the purposes of allowing the renderer and physics to do their thing, whenever you set `transform.localEulerAngles`.

Whenever you need the source values, you have them stored right there in your class and can perform your own necessary pre-checks upon them. You are then not relying on Unity's internal representations, as you have your own to hand.
> 1 votes

---
Tags: unity, quaternion, euler-angles
---


# Question
Title: How to create additional rooms for new play sessions in a 2-player online game on Node.js?
I'm creating a 2-player online game using Node.js with Express and Socket.IO

My task is to create a new room when 1st, 2nd, etc ... rooms are full. From this article I know how to create one room for all connections:

```
// require everything you need
var io = require('socket.io').listen(server);
io.on('connection',function(socket){
    // creating socket.player with unique ID
    socket.on('anyeventfromconnectedplayer', function doSomething () {...
    });
});

```

How to create new rooms for new play sessions?

Socket.IO has a mechanism to implement the thing I need but I don't understand how to use it correctly.

# Answer
I would suggest not using Socket.IO's rooms mechanism. It is not very flexible and isn't very appropriate for a robust server architecture.

Here's a quick scribble of how you could structure your rooms on the server. Obviously you'll want to use your own class for Player instead of the socket object, lookup rooms by id etc, but I wanted to keep the example short.

```
function Server(io) {
    this.players = {}
    this.rooms = []

    io.on('connection', (socket) => {
        let player = this.players[socket.id] = socket

        let openRoom = this.findOrCreateRoom()
        openRoom.players.push(player)
        player.currentRoom = openRoom

        player.on('playerAction', (msg) => this.routeMsgToRoom(msg, player))
    })
}

Server.prototype.routeMsgToRoom = function(msg, player) {
    if (!player.currentRoom) throw `Player ${player.id} is not in a room!`

    player.currentRoom.handlePlayerMsg(msg, player)
}

Server.prototype.findOrCreateRoom = function() {
    let room = _.find(this.rooms, r => r.players.length < 2)
    if (!room) {
        room = new Room()
        this.rooms.push(room)
    }
    return room
}

function Room() {
    this.players = []
}

Room.prototype.handlePlayerMsg = function(msg, player) {
    //do something
    _.each(this.players, p => p.emit('actionHappened', { roomData: 42 }))
}

```
> 2 votes

---
Tags: node.js, online, websocket
---


# Question
Title: Frustum culling with a single large object
I am helping to optimize performance in a mobile game. The artists who built a particular scene added a wall around the scene. The wall is a single mesh with 100k triangles. Because it goes around the entire scene, at least some of the wall is visible from all angles and is always being rendered.

While running the game in the Editor with the Statistics panel enabled, I can see that hiding the GameObject containing the wall always reduces the current number of tris by 100k regardless of how much of the wall is actually visible. Does this mean that the *entire* wall is always getting rendered, rather than only the triangles that are actually in front of the camera?

Obviously the artists need to reduce the overall polygon count of the wall, but I'm wondering if they should also break it into several separate pieces so that the entire wall doesn't need to be rendered at once.

# Answer
The entire mesh is indeed being sent to the GPU for rendering. It’s up to OpenGL (or whatever graphics library) to determine what to do with it. Frustum culling only works by disabling whole meshes that are entirely outside of the camera’s view. However, the actual rendering is only done for the fragments (pixels) that are onscreen and not obscured by something in front of it in the depth buffer (assuming the shader is set up to work with the depth buffer).
> 2 votes

---
Tags: unity, performance, frustum-culling
---


title: MonoGame Save Game Location Example

text:
# Question
Title: MonoGame Save Game Location Example
I am building a game using Monogame 3.6 and Visual Studio Community 2017. Up until this point I have been serializing the data using BinarySerialization and created a custom `ContentImporter` and `ContentProcessor`.

My question is what is the standard used for saving game data and where is it saved? I attempted to use the `IntermediateSerializer` class, but that was stored in XML and is easily modified. I would like to store the game data in a file that is more difficult to tamper with, which is why I chose binary serialization.

I would also like to see an example of code that uses the standard for file paths when saving to the file system. On my development system, I can save anywhere because I am Administrator. But I would like to understand which parts of the framework are available for me to get file path information and save the data.

# Answer
> 1 votes
I'm going to assume from your question that you are working on a Windows game. The recommended location for most gamesaves would be under your users's `AppData/Roaming` folder. If you are using UWP then this is fairly easy to do as you can use the `ApplicationData.Current.RoamingFolder` to access it using the storage classes in UWP. The docs on this have a good example of saving a file.

Now that's just for Windows, each platform will have different locations and requirements for storing this kind of information. One tip I would have is have a common function for writing to files, like so:

```
public void SaveGame(string filename, string data) {
#if WINDOWS
    // save game on Windows
#elseif ANDROID
    // save game on Android
#elseif OTHER
    // ...
#endif
}

```

This reduces the hassle of maintaining file systems. As for the format of the file, that is essentially up to you, I can't think of any reason you can't format it however you want.

---
Tags: monogame, savegame
---


# Question
Title: How can I protect beta test versions of my game from piracy?
I want to open my game for public feedback and testing quite early as such certain features like steams coming soon might not be available.

How could I protect my game against being pirated around from testing?

Even if we dis-regard piracy I'd not want the testers running random copies of the game whenever etc.

# Answer
Why worry about piracy at all in this case? If it is a beta version, then it will give players an idea how the finished game is going to look and play, but it would be buggy and incomplete. The game experience will be suboptimal, and the player will understand that this is because they are playing an incomplete version of the game. If they like the game, then they will want to buy the complete version so they can experience it as intended. A leak of an early beta version might in fact be free advertisement which ends up giving you more sales than it prevents.

But if you are really worried about this for some reason, for example because your beta is actually an almost complete release candidate, there are some things you can do.

* Charge people for beta testing your game. Call it "Early Access". Take the same anti piracy precautions you would take for the actual game.
* Ask your lawyer to write you a non-disclosure agreement which allows you to sue your beta testers when they leak the beta. Ask your beta testers for their real names and home addresses. Send them the agreement by snail-mail, ask them to sign it and mail it back to you. Having a signature on a physical document doesn't just make it *feel* more real, it also ensures that you know the real identities of your beta testers. Then give each tester a built of the game with a hidden personalized watermark, so you can tell it was them when it ends up on pirate bay (or at least tell them you did that).
* Rely on the DRM features of your distribution platform. The Apple app store, for example, offers the Test Flight program which allows you to run closed beta tests for unpublished apps. You can also run closed beta tests on Steam. Other distribution platforms offer similar services. And as a side-effect, you also earn some first-hand experience with your distribution platform. This experience will be very valuable on launch day.
* If you have access to physical office space, only allow people to test the release candidate on premise.

I'm looking forward to testing your game.
> 5 votes

# Answer
What I have seen many developers doing lately is to distribute early-access games on itch.io that don't make the full game available. Kind of like a demo but you can include and structure your builds however you want to get player feedback. Usually the home screen of the game indicates that it is an unfinished, early-access build. That way even if somebody distributes the test build, it's only a small part of the game. Then, when the game is complete, I've seen some developers remove the game from itch.io in preparation for a steam release. Steam currently offers some measure of DRM options that itch does not, but that could change.
> 2 votes

# Answer
In case of single-player game: beta version can be a demo (shor) version of game.

In case of multiplayer game: limit amount of users and wipe instance after release.

Possibly "A non-disclosure agreement (NDA)" that If your testers can sign it.

About Ideas and conceps - Sadly there is no options. The only thing you can do - is finish game and release.

You can host some parts of game (resources or data) on some server. This server can also collect information about running game instances, crashes, and so on. And game simply not working without connection to this server. So when yout test period ends - shutdown your server.

It may save you from most common cases of piracy.
> 0 votes

---
Tags: playtesting, piracy
---


title: Implementing win condition

text:
# Question
Title: Implementing win condition
I'm making a turn based game in java for fun, it follows a set game flow pattern contained in a loop. I realized that once a player hits a win condition the game continues playing out the rest of the turn, possibly changing the victor.

Do I need to go back and put `if` statements everywhere so nothing is executed once a victor is declared? Is there a more elegant solution?

# Answer
> 1 votes
Instead of doing that, just make sure to not allow the game to change the victor. If your language has getters and setters, then inside the victor's setter check if it already has been defined. Only change it, if it wasn't. If it doesn't support native setters, then simply create a setter method with the same goal and make the variable private.

# Answer
> 0 votes
you should break the loop when the condition is reached. most programming languages provide mechanismens to break a loop.

example language:

```
do{
    player.performAction();
    boolean playerHasWon = checkPlayerWinCondidtion();
    if( playerHasWon){
        //maybe perform other actions here, ut later and ultimatly...break
        break; //breaks the loop here
    }
    opponent.performAction();
    boolean opponentHasWon = checkOpponentWinCondition();
    if(opponentHasWon){
        break; //breaks the loop here
    }
while(true);

```

not that you need an endless loop, just as an example...

anyway for your question: yes, you answered that thign already correct. you have to use if statements, that would be the proper way to do it... there are fancy ways of programming such stuff but in the end it is the right way to do it.

---
Tags: java, turn-based
---


title: How to test if a level is passable?

text:
# Question
Title: How to test if a level is passable?
I am making an classic 2D arcade ball game. There will be 100 levels in this game. And after the 80th level passing the level by doing some arcade stuff will be very difficult.

For example level 100 will be the most difficult level and if I can't pass this level with manual testing (I am not very skillful), how can I know without manual testing if the 100th level can be passed?

(I don't want to make an impossible level. I just want to make a very difficult level.)

# Answer
My advice would be to **test each obstacle independently**. Since you are using a level editor, make the best out of it by manually moving the player to the obstacle in the editor and then try it. If you can pass all of the obstacles independently then your level is possible.

If you are not skilled enough you can still ask a friend or another person with more skills to do this task. You can simplify this by adding really regular checkpoint (or similar teleportation system) that you can easily navigate with some debug inputs.

Something I tend to do to test my game is create debug functions like **slow motion**, **invincibility**, or **infinite ammo** to test the features I just created. It could help you test your game even if you are not skilled enough. Of course you have to remove these debug functions before releasing your game haha.
> 2 votes

# Answer
It helps if you understand your game mechanics very well to gain an understanding of what is and is not possible.

For example, knowing the acceleration and maximum speed of your player character tells you if it is theoretically possible to move a certain distance in a certain time. *You* might not be able to pull it off, but if you do the math, you can calculate that it is possible if the player inputs are accurate within `x` ms, which you consider within the abilities of the best players.

But theoretical understanding of your game is no replacement for the one most important thing when it comes to understanding a game: **get testplayers**. Find many testplayers of many different skill levels. When you aren't skilled enough to beat your own game, find someone who is. When you can't find anyone who succeeds even after lots of training, then succeeding might not actually be possible.

You can't find good testplayers? Then you can take the programmer's solution and just program your own. Add a system for controlling the player-character with pre-programmed timed inputs. Then figure out a sequence of inputs which beats a level. This might be a bit tedious, but it really pays off, because now you also have an automated test suit. Whenever you make a code change, run your test suit. If it fails to complete the levels it managed to complete before, you broke something. If it still succeeds, you know your game still plays like it used to. Such automated test suits can be a great time-saver when it comes to finding bugs. For a real world example, check out the video of the test suit for the game Factorio.
> 1 votes

# Answer
Without knowing more about your game, this is the solutions I see available to you:

1. Get better at your game, and make sure that you can actually finish the levels by hand.
2. Game testers tend to become very good with the games they test, so you can find someone to test your levels. They may already be good with the type of game you're making, or they'll become good enough to make sure that the levels are either completable, or too hard.
3. Build an AI to play your game as a normal player *could* play. If the AI is not able to finish the level, then your level is not passable or you need to work on your AI more. That's very dependent on *your game* so this falls out of the scope of this answer. You should ask another much more precise question if you want to attempt that.
4. Don't manually test these too-hard-for-you levels, release the game and wait your players to complain. You'll know that the levels are too difficult or not passable.

Solutions 1 and 2 will help you decide how to sort your levels in terms of difficulty from a player point of view, while solution 3 could do it from a theoretical point of view.

Solution 4 will bring you low ratings and bad comments on the multiple plays stores where you'll release your game, but it is the fastest and the easiest.
> 1 votes

---
Tags: level-design, testing, playtesting, difficulty
---


title: How can I store my 2D map in JAVA?

text:
# Question
Title: How can I store my 2D map in JAVA?
I'm working on a 2d adventure game where the player can explore a random generated map. It's working perfectly if I set it to be about 3000x1000 blocks (my array is 3000x1000x2), but this is TOO SMALL. When I want to make a bigger map it trows an OutOfMemory error.

I store my map in a 3d float array where the first two dim shows the position on the world plus I need 2 more data (3rd dim) for each block the type (int blockID) and the stored last update time (float elapsedTime).

Can it be better if I make it 2 separeted 2d array?

This 3d array is the one what is too big and trows OutOfMemory error. The blocks that have made Objects are the ones that can be seen(~32x14 block) the other are just two number ID and elapsedTime.

How should I store the map data?

EDIT:

This code: `int x = 10000;
 int y = 10000;
 float[][][] ft;
 ft = new float[x][y][2];` It trows OutOfMemory error.

# Answer
When your game has a map which is too large to fit into memory, then the default solution to the problem is to use chunks.

Divide your map into rectangular chunks which are about as large as the screen. Only load the chunk the player is in and the adjacent chunks into memory. When the player moves to a different chunk, persist the no longer needed chunks to the file system and unload them (which you do in Java by making sure that there are no variables anymore which point to them). When the player returns, load the chunks from the file system back into memory.

When your map is randomly-generated, then you can use the fact that the Java `Random` class can be initialized with a seed value. When you call `new Random(seed)` with the same seed, you get the same sequence of random numbers from it. So when you use a new Random object for each chunk you generate, then all you need to save about a chunk is the seed value and any changes to the chunk which happened over the course of the game.
> 1 votes

# Answer
You have a three dimensional float array of the size \[3000,1000\]? Well thats two dimensions?

Ignoring that: that are 3 million floats with 8 bytes each (there seems additional overhead if you use Float insead of float) = 24 million bytes = 24 mega byte. Seems not too much for a usual memory in a pc.

May tunning the memory settings will help you temporarily: Java memory settings

To calculate the actual size you store may that SO question will help you.

From my experiences with tilemaps: yes, they can become large in memory even if you trim down every single byte possible. (think I was up to 8 - 12 GB ram in my experiments for the tile map array only.)

But in fact you most likely do not need all the data in memory all the time. Since you generate a map may try to store that created map in a file and load (and update on demand) only the area near the player. So you can limit your memory demand.

---

Possible improvements of the data structure of the tilemap

If you have a 3 dimensional map where the third dimension are tiles stacked up you still could use a short or integer array (depending on the needed amount of tiles) instead of a float array saving some bytes. The short/int indicates the tile type.

The tiles themselves can be stored in a seconds structure like an array which holds all the data needed for this specific tile type.

I have to guess but I think you used the float "as drawing position"? Iterating over the array while drawing gives you the x,y,z tile indizes and you could calculate the drawing position out ouf the tile index you already have at this point. Which makes it unnecessary to store them.
> 0 votes

---
Tags: java, 2d, tilemap, memory-efficiency
---


# Question
Title: How to better refactor loops in procedural world generation?
One of the steps for cell-based dungeon generation is deciding the amount and location of exits for each room. My current set up consists of the following:

1. Define my exits. There are 15 types of room exits:

* Left (L), Right (R), Top (T), Bottom (B).
    * Every non-redundant combinatoric of two directions (LT, TR, RB, BL, LR, TB)
    * The same for three directions (LTR, TRB, RBL, BLT)
    * All directions (LRTB)
2. Create a list `exitsList` that contains the type of exit of that index, i.e. `exitsList[0] = L` means that our first room has a single exit: one to the left.

After creating my basic level layout and having my exit generation ready, it's time to go back to each room and assign its exits, and **this** is the part I'm having my doubts about.

Currently, my method for assigning rooms is to make a case check looping through each cell. Something such as:

```
for (each room){
    switch (exitsList[this_room]) {
        case L:
            place_exit_L;
            break;
        case LT:
            place_exit_L;
            place_exit_T;
            break;
        case TR:
        .
        .
        .
        case LTRB:
            place_exit_L;
            place_exit_T;
            place_exit_R;
            place_exit_B;
            break;
        default:
            return_error;
            break;
    }
}

```

While this can work, it seems very inelegant, and more importantly obnoxious to read by a human. I was able to refactor cases that shared the same type of exit by omitting breaks, for example:

```
case LTR:
    place_exit_R;
case LT
    place_exit_T;
case L
    place_exit_L;
    break;

```

But this seems rather arbitrary. I suspect there's a more efficient way to do this, or at least one that won't become a pain to read by other people if the number of exits somehow increases.

# Answer
> 4 votes
Use four attributes instead of one for expressing the types of exits for a room.

```
for (each room){
    if (room.has_left_exit){
        place_exit_L;
    }
    if (room.has_top_exit){
        place_exit_T;
    }
    ...
}

```

# Answer
> 5 votes
Building on the answer from @congusbonus, if you are committed to using a single variable in an array as you have shown, you can define each combination in such a way that encodes each direction as a single bit in a bitmask:

```
int T = 1;
int L = 2;
int B = 4;
int R = 8:

int TL = T | L;
...

for (each room){
    int exits = exitsList[this_room];
    if (exits & L == L){
        place_exit_L;
    }
    if (exits & T == T){
        place_exit_T;
    }
    if (exits & B == B){
        place_exit_B;
    }
    if (exits & R == R){
        place_exit_R;
    }
}

```

---
Tags: 2d, procedural-generation, data-structure
---


title: How Can I Fix Where The Tile Spawns?

text:
# Question
Title: How Can I Fix Where The Tile Spawns?
I am making a 3D game in Unity and C#. I want to spawn another tile when the player is at the end of the current tile. But when I spawn the next tile it doesn't spawn at the right place(just after the current tile). How can I fix this?

Thanks

Old Code:

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

public class Terrain : MonoBehaviour
{
    public List<GameObject> objs = new List<GameObject>();
    public GameObject terrain;
    public GameObject player;
    private float z = 4130.875f;
    private float safeZone = 260.0f;
    private float tileLength = 260.0f;
    private int animTilesCount = 2;
    void Start()
    {
        for (int i = 0; i < animTilesCount; i++)
        {
            spawnTile();
        }
    }
    void Update()
    {
        if (player.transform.position.z - safeZone >= (z - objs.Count * tileLength))
        {
            spawnTile();
            DeleteTile();
        }
    }

    public void spawnTile()
    {
        GameObject go;
        go = Instantiate(terrain) as GameObject;
        go.transform.SetParent(transform);
        go.transform.position = Vector3.forward * z;
        Debug.Log(z);
        Debug.Log(Vector3.forward * z);
        Debug.Log(go.transform.position);
        go.transform.rotation = terrain.transform.rotation;
        objs.Add(go);
        z += tileLength;
    }

    public void DeleteTile()
    {
        Destroy(objs[0]);
        objs.RemoveAt(0);
    }
}

```

That's the position of the current tile.

The correct position for the next tiles would be (6.103516e-05, 3.051758e-05, z). They have to spawn after the current tile.

# Answer
> 0 votes
If you just want to spawn at an offset from the previous tile, did you try reading the position of the previous tile, and adding onto that?

Just make sure your `objs` list is initialized in the Inspector.

```
public Vector3 nextTileOffset;

public void spawnTile()
{
    Vector3 position = objs[objs.Count - 1].transform.position;
    position += nextTileOffset;

    GameObject go = Instantiate<GameObject>(
                      terrain,
                      position,
                      terrain.transform.rotation );

    go.transform.SetParent(transform);

    objs.Add(go);
}

```

---
Tags: unity, c#, game-design, game-mechanics, tiles
---


# Question
Title: How to implement the seek steering behavior in Unity3d?
Following this tutorial: Understanding Steering Behaviors: Seek, I tried to add seek and steering behavior to my Unity prototype but it's not working this is my script. The cube does not steer it just follows the target.

```
public GameObject target;

    float maxForce = 15;
    float maxSpeed = 30;
    float maxVelocity = 200;
    float mass = 15;

    Vector3 velocity;

    void Start() {
        velocity = Vector3.zero;
    }

    void Update() {
        transform.LookAt(target.transform);

        var desiredVelocity = target.transform.position - transform.position;
        desiredVelocity = desiredVelocity.normalized * maxVelocity * Time.deltaTime;

        var steering = desiredVelocity - velocity;
        steering = Vector3.ClampMagnitude(steering, maxForce);
        steering = steering / mass;

        velocity = Vector3.ClampMagnitude(velocity + steering, maxSpeed);
        transform.position += velocity * Time.deltaTime;

    }

```

What could be the problem??

# Answer
> 3 votes
I had to make some adjustments to the values this works perfectly.

```
   public float Mass = 15;
    public float MaxVelocity = 3;
    public float MaxForce = 15;

    private Vector3 velocity;
    public Transform target;

    private void Start() {
        velocity = Vector3.zero;
    }

    private void Update() {
        var desiredVelocity = target.transform.position - transform.position;
        desiredVelocity = desiredVelocity.normalized * MaxVelocity;

        var steering = desiredVelocity - velocity;
        steering = Vector3.ClampMagnitude(steering, MaxForce);
        steering /= Mass;

        velocity = Vector3.ClampMagnitude(velocity + steering, MaxVelocity);
        transform.position += velocity * Time.deltaTime;
        transform.forward = velocity.normalized;

        Debug.DrawRay(transform.position, velocity.normalized * 2, Color.green);
        Debug.DrawRay(transform.position, desiredVelocity.normalized * 2, Color.magenta);

    }

```

---
Tags: unity, c#, 3d
---


# Question
Title: Potential Field Pathfinding in a non Axis Aligned World
I am trying to create a game that has player created obstacles which can be placed anywhere in free space, and which has a large amount of enemy agents. In persuit of maximizing the number of agents I can have active at any given time, and as a secondary goal of maximizing the possible size of my map, I found potential/vector fields to be a very appealing solution, except for one thing.

Since the geometry is not aligned to any particular grid I have the problem of what to do when I have a narrow alley between obstacles that is approximately the size of one of my units (As such:)

In this case, cells approximately the same size as the unit would consider this route impassable. One solution would be to use a smaller size of cell, but this of course means more computational resources. Does anyone know of an alternative solution to this problem?

# Answer
> 1 votes
Since your geometry does not have to be axis aligned, an AA grid does not seem like a good data structure for the pathfinding. I think you can consider several approaches.

* Adaptive grid - grid which will be finer close to non-AA edges and coraser elsewhere. Something in terms of quad-tree. The potential field would then work regularly and your grid would be axis aligned.
* Convex polygons connected by choke points - if your maps will look like StarCraft maps, where there are mostly convex areas connected by chokepoints, you can do very simple navigation inside the areas and have special handling of choke points. This is not a solution by itself (it does not solve the problem), it's just an idea to think about.
* Triangular or quad navmesh \- if your maps will be more complicated you can partition the ground into triangles/quads which will not be axis aligned such as when working with navmeshes. Then in each of these nodes, you would have your vector field vector. Of course, some care needs to be taken when generating the navmesh since we would prefer equally sized triangles.
* Steering - another approach different from vector fields is to implement steerings, where agents are attracted to goals and repelled from obstacles. Steering tutorial. **Edit:** if you are interested in different steering behaviors of multiple agents check out Boids. Also some more about steering from the same author here.

---
Tags: ai, path-finding
---


# Question
Title: Can I use Adobe Fuse CC models in my commercial game?
I'm wondering if it's allowed to use Adobe Fuse CC models and textures in a commercial game?

I use this software to get good shapes of character and then use Blender to modify the body or renew texture.

# Answer
> 3 votes
Yes, you can.

See the PDF document that can be found here on Adobe's website.

Additionally, this page on Adobe's forums describes a bit more in layman's terms what you can and can't do with Adobe Fuse CC.

In summary, you can produce commercial games and DLCs for your commercial games, but you can't produce assets that you will sell on different assets stores.

---

For your convenience, here is the relevant part of the PDF:

> 1. Additional Definitions:
>
> 1. Animation Data means 1) animation files in BVH, FBX, OBJ or Collada formats containing data owned by or licensed to Adobe; and 2) Fuse 3D animation models.
>     2. End Use means the derivative application or product created by you, into which the Animation Data, or derivations thereof, is embedded, for your use or your customer's use.
>     3. User Characters means the 3D characters created by you or provided by you using 3 rd party software.
> 2. License Grant. Subject to your compliance with the Terms, Adobe grants you a personal, non-exclusive, non-sublicensable and non-transferable license to use the Animation Data to create an End Use. You may reproduce and distribute Animation Data only in connection with the End Use. You may modify the Animation Data prior to embedding such Animation Data in the End Use. Redistribution, republication or commercialization of Animation Data separate from or outside of the End Use is strictly prohibited.
> 3. Restrictions. Except as expressly granted in Section 2 (License Grant), you cannot (i) modify, reverse engineer, copy, reproduce, republish, upload, or (ii) rent, lease, sell, transmit, sublicense or otherwise distribute the Animation Data.
> 4. Proprietary Rights. Other than the rights granted herein, Adobe retains all right, title and interest in and to the Animation Data. Except as expressly granted in Section 2 (License Grant), you have 1) no rights to modify or make derivative works of the Animation Data, and 2) no license, right or interest in any Adobe patent, trademark, copyright, trade name or service mark is granted hereunder. You agree not to export the Animation Data in violation of UN embargoes or US laws and regulations.
> 5. User Characters. You may use and modify User Characters in connection with the Services and the Animation Data.

Note that this not the complete license that comes with the software, and in any case replaces it; you should read and agree with the license that comes with the software.

---
Tags: models, licensing
---


# Question
Title: Why do we need a depth buffer to display a single 3D cube?
According to a Vulkan tutorial I am following, I will need to create a depth buffer in order to display a 3D cube:

However, as far as I understand, depth buffers are used for the Z-buffering technique, which helps one efficiently calculate occlusion effects. If I have a single 3D cube in a scene, there is never going to be any occlusion. So why would I need a depth buffer?

# Answer
*Posting as answer as requested by OP.*

If you render your primitives without face culling, then the system needs the depth buffer to tell which of the faces of the cube are on the front and which are on the back.

Without depth buffer and without face culling it will render in the order you specify the faces, which will result in some faces that should be on the back of the cube being incorrectly drawn on top.

It should be possible to decide in CPU what faces to draw using the painter's algorithm, which is perfectly suitable for rendering acube. However, that is slower.

**Note**: The painter's algorithm will fail if faces intersect or if trying to sort them by overlap order results in loops.

Thus, you do not really need depth buffer in this example. In the sense that it could have been archived by other means (face culling or painter's algorithm). Yet, you will need depth buffer for more complex scenes, probably the author wanted to introduce the use of depth buffer in a simple setting.

---

Recommended viewing (graphics API agnostic): Pixels and Triangles - Computerphile playlist \- the fourth video on the series (The Visibility Problem) explains the problem of what to do draw ontop of what and approaches to solve the problem.
> 2 votes

# Answer
If you want it to draw correctly, that is, with the planes in the back staying in the back, and the planes in the front staying in the front, you need depth buffer. The depth buffer is used to determine what stays in front of what, even for the smallest 3D primitive: a single vertex point.

This is a case (https://stackoverflow.com/questions/6159385/opengl-z-index-problem) of cube rendered without the depth buffer:

Notice that the planes are drawn in the order they are sent to the GPU, not taking in account their 3D position.
> 2 votes

# Answer
For a single non-self-shadowing mesh you don't need a depth buffer, managing draw order and proper winding+culling settings will be enough.

However as soon as you want something more complex or want to draw arbitrary meshes you need the depth buffer to avoid weird effects.

So the tutorial will teach you how to add depth testing, especially because in vulkan it's less trivial than in old-school graphics apis.
> 1 votes

---
Tags: rendering, depth-buffer
---


# Question
Title: IndexOutOfRangeException: Array index is out of range even though the inspector clues otherwise
I am currently making a randomized infinite platform with GameObject already made platforms in 3 arrays. In the inspector everything is obviously running quite smoothly but I keep weirdly keep getting uncalled for errors like: **IndexOutOfRangeException: Array index is out of range.**

**Here is my code:**

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

public class BackFloorSetter : MonoBehaviour {

    public GameObject[] gameBackFloorsOne;
    public GameObject[] gameBackFloorsTwo;
    public GameObject[] gameBackFloorsFinal;

    public Vector3 nextPosition;

    public float unroundedFinalOrTwo;
    public int finalOrTwo;

    public float unroundedTwoFloor;
    public int twoFloor;

    public float unroundedFinalFloor;
    public int finalFloor;

    public GameObject currentSpawnFloor;

    public float floorSpawnCounter;

    public int counterGoal = 5;

    void Start()
    {
        nextPosition = new Vector3(0, 0, 0);
        Instantiate(gameBackFloorsOne[0], nextPosition, Quaternion.identity);
    }

    void Update()
    {
        floorSpawnCounter += 1 * Time.deltaTime;

        if(floorSpawnCounter == counterGoal)
        {
            floorSpawner();
            counterGoal += 5;
        }

        unroundedFinalOrTwo = Random.Range(0.6f, 2.4f);
        finalOrTwo = Mathf.RoundToInt(unroundedFinalOrTwo);

        unroundedTwoFloor = Random.Range(-0.6f, 3.4f);
        twoFloor = Mathf.RoundToInt(unroundedTwoFloor);

        unroundedFinalFloor = Random.Range(-0.6f, 4.4f);
        finalFloor = Mathf.RoundToInt(unroundedFinalFloor);

        if (finalOrTwo == 1)
        {
            currentSpawnFloor = gameBackFloorsTwo[twoFloor];
        }
        if (finalOrTwo == 2)
        {
            currentSpawnFloor = gameBackFloorsFinal[finalFloor];
        }
    }

    public void floorSpawner()
    {
        nextPosition.x -= 232;
        Instantiate(currentSpawnFloor, nextPosition, Quaternion.identity);
    }

    public void flatGroundSpawner()
    {
        nextPosition.x -= 232;
        Instantiate(gameBackFloorsOne[0], nextPosition, Quaternion.identity);
    }

}

```

# Answer
> 2 votes
I can't say for sure, but in here:

```
unroundedTwoFloor = Random.Range(-0.6f, 3.4f);
twoFloor = Mathf.RoundToInt(unroundedTwoFloor);

```

`unroundedTwoFloor` could very well be `-0.6f`, which means that `twoFloor` could become `-1`.

# Answer
> 0 votes
To fix the out of range issue I changed the two unrounded values to something that would correctly round to a correct value; **New Code**

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

public class BackFloorSetter : MonoBehaviour {

    public GameObject[] gameBackFloorsOne;
    public GameObject[] gameBackFloorsTwo;
    public GameObject[] gameBackFloorsFinal;

    public Vector3 nextPosition;

    public float unroundedFinalOrTwo;
    public int finalOrTwo;

    public float unroundedTwoFloor;
    public int twoFloor;

    public float unroundedFinalFloor;
    public int finalFloor;

    public GameObject currentSpawnFloor;

    public float floorSpawnCounter;

    public int counterGoal = 5;

    void Start()
    {
        nextPosition = new Vector3(0, 0, 0);
        Instantiate(gameBackFloorsOne[0], nextPosition, Quaternion.identity);
    }

    void Update()
    {
        floorSpawnCounter += 1 * Time.deltaTime;

        if(floorSpawnCounter == counterGoal)
        {
            floorSpawner();
            counterGoal += 5;
        }

        unroundedFinalOrTwo = Random.Range(0.6f, 2.4f);
        finalOrTwo = Mathf.RoundToInt(unroundedFinalOrTwo);

        unroundedTwoFloor = Random.Range(-0.4f, 3.4f);
        twoFloor = Mathf.RoundToInt(unroundedTwoFloor);

        unroundedFinalFloor = Random.Range(-0.4f, 4.4f);
        finalFloor = Mathf.RoundToInt(unroundedFinalFloor);

        if (finalOrTwo == 1)
        {
            currentSpawnFloor = gameBackFloorsTwo[twoFloor];
        }
        if (finalOrTwo == 2)
        {
            currentSpawnFloor = gameBackFloorsFinal[finalFloor];
        }
    }

    public void floorSpawner()
    {
        nextPosition.x -= 232;
        Instantiate(currentSpawnFloor, nextPosition, Quaternion.identity);
    }

    public void flatGroundSpawner()
    {
        nextPosition.x -= 232;
        Instantiate(gameBackFloorsOne[0], nextPosition, Quaternion.identity);
    }

}

```

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


title: Libgdx loading images

text:
# Question
Title: Libgdx loading images
I can't find a sulotions that solves my problem, I've tried pretty much every tip I can find, but with no luck.

Error :

`Exception in thread "LWJGL Application" com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load file: assets/enemy.png`

From code:

`enemyImg = new Texture(Gdx.files.internal("assets/enemy.png"));`

I've linked the asset file from android to desktop as I am supposed to. But still, no luck, the asset file in my desktop-project doesn't even update when I add my image to my android projects asset file.

Please help so I can get started :)

EDIT: Managed to load png now, but I have to manually put the picture in the desktop projects asset folder, so would still appriciate an answer on how to do it automaticly

# Answer
> 4 votes
The "Couldn't load file" error message you see is caused by two possible things:

* The path is invalid (probably this one)
* The file format is not supported (rare, but possible what OS are you using? I have seen this with Macs)

First, check if the path is truly correct. Check this:

```
Gdx.app.log("AssetPath", Gdx.files.internal("assets/enemy.png").file().getAbsolutePath());

```

Make sure that path is valid, and if not correct it. (You can copy and paste it into a file browser and that should be good enough to check.

Second, check what settings/format you used to save the png file. I don't believe indexed png files are supported with libgdx. Try adjusting the settings you used to save the file and reload it. I have seen issues with MacOS X saving png files and not being able to load them in Windows/Android via libgdx.

If you are still having issues after all this, take a screen capture of your project folder, showing the asset files. Additionally, post the image file so someone might be able to identify the issue you are having.

**Edit**:

To answer the other part of your question I will assume you are using Eclipse.

Firstly, the asset folder in the desktop project isn't actually a folder. If you have a folder, delete/remove it. What you are instead doing is trying to create a symlink between the two projects to 'share' the same folder.

In your Desktop Project you should only have /lib and /src and some library references:

1. Select the Desktop Project folder in Eclipse, Right-click \> Build Path \> Link Source...
2. Click Browse..., navigate your file system and find the asset folder for the Android Project
3. Set the folder name to be "assets" if it isn't already
4. Press finish

Now when you build your desktop project, the assets folder in the android project will be treated as a source folder. All non-java files are copied into the /bin folder with your class files. When you change a file in the android asset folder, it will automatically get copied into the output folder.

# Answer
> 0 votes
`Gdx.files.internal` already looks inside the assets directory, so it's unnecessary to use "assets/enemy.png" - you could use just "enemy.png" instead.

---
Tags: libgdx, image
---