title: How to insert animation into table?

text:
# Question
Title: How to insert animation into table?
I'm having trouble inserting animation into my libGDX table cell. I have a class which holds 2 tables, one on the left and one on the right. First table is for labels/buttons/other stuff. Second table is for animation, which should change if user clicks a button.

I've created `Animation` class which holds up different animations. The problem is that when I try to add an animation class into the table cell, I get an error because my `Animation` does not extend nor implement `Actor` class, thus I can't insert it into the cell. What should I do? How do you insert class of type animation into table cell?

# Answer
> 0 votes
You probably want to extend the Image class yourself and implement the Act method to update the animation state time.

```
public class Animation extends Image{
    private float stateTime = 0;
    private Animation<TextureRegion> animation;

   public AnimatedActor(Animation<TextureRegion> anim) {
     super(animation.getKeyFrame(0));
     animation = anim;
   }

   @Override
   public void act(float delta){
  ((TextureRegionDrawable)getDrawable()).setRegion(animation.getKeyFrame(stateTime+=delta, true));
super.act(delta);
      }
 }

```

If you want more control over the animation you could even oerride the draw method and draw it yourself.

```
@Override
draw(Batch batch, float parentAlpha){
   // draw your animation here
}

```

---
Tags: java, libgdx, android
---


title: Do i lose performance doing this

text:
# Question
Title: Do i lose performance doing this
```
 public class TileObject : MonoBehaviour {

////some code was here
public PlayerAnimator playerAnimator;

////some code was here

public void SetTileObject(int xPos, int yPos, TileData tileData)
{
   ////some code was here

    if (tileData.player)
        playerAnimator = new PlayerAnimator();
}

```

And my question do i lose any performances(or memory) doing this instead of inheritance or something else.(tileObject can be other than player)

# Answer
There doesn't seem to be anything resource-intensive in your question. You are falling victim of Premature Optimisation. From a design point of view, your idea is similar to organising objects with component (rather than inheritance). Each of them has its own ups and downs, and sometimes different uses.

Which of them is faster? Does it really matter? They've both been used by professional game engines, so they both can create promising results.
> 2 votes

---
Tags: unity, performance
---


# Question
Title: Unity3D - Mesh appears black in parts that it shouldn't
I have a procedurally-generated mesh that I am generating to use as a terrain. It looks something like this (from above, and it changes slightly every time):

It also looks fine when I view from the z-axis side.

The issue is that when I view it facing the x-axis, it has a black part kind of going through it.

I wouldn't really care about that, but when the player goes into the valley, it seems as if they fall under the black part. They can only see the ground and above them it is all black.

The mesh does have a mesh collider attached, and so the player doesn't fall the way through the mesh - just the "black line". The height of the mesh (on the y-axis) is generated using perlin noise that I multiply by 800 (to increase the waviness), and that is set when I set the vertices. I suspect that this issue has to do with the normals or the uvs not adjusting to the y-axis, but I've messed around with it a lot and nothing seems to help. I currently generate the normals with RecalculateNormals() after I generate the vertices, triangles, and uvs, and calculate the uvs in a for-loop where I take each vertex's x and z axis and divide it by the number of vertices on that axis time the distance between them (to make it between 0 and 1).

# Answer
> 0 votes
I figured it out, and it had nothing to do with UVs or normals like I had thought. Actually, there was a problem with how the triangles were generating - most of the last row's triangles were put at the wrong positions and at the wrong angle, leading to the black line crossing the mesh. Fixing the triangles fixed the problem.

---
Tags: unity, mesh
---


# Question
Title: How to create a wind tunnel / sky diving effect like in Fortnite?
I am using Unity and I want to create a sky diving effect, as if you were looking directly down while falling and have the wind fly past you. My guess is I have to do something with the particle system. How can I do this?

An example is this video of Fortnite https://youtu.be/JFHs3uNJ9Cw?t=23s, you can see the wind flowing from the characters hands and feet.

# Answer
It looks like you can accomplish a similar effect by...

1. Attach an object with a TrailRenderer component to each point on the model that should send out streaks (eg. the hands & feet)
2. Set the material on the trails to use a wispy, cloudy texture, and pan it the texture down the trail over time to create a blowing/streaking effect.
3. Set the TrailRenderer's colours so that the trail fades to transparent by the end of the ribbon.

Make sure to test on an object in motion so you can see how the changes affect the trails. A stationary object won't leave trails behind it.
> 4 votes

# Answer
You could use a combination of a Trail Renderer and Particles. The particles should be set to world space and attached to the character to recreate a "trail effect". There is a plenty of tutorials on youtube on how to do good looking particles ! The trick here is really "world space" particles.
> 0 votes

---
Tags: unity, particles
---


# Question
Title: How to instantiate prefab outside Resources folder?
I'm trying to developing a tool to help me "remember" all my prefabs / fbx assets.

My assets are almost in a subFolder (for instnace) "3d models" .

I've developed a routine to get all "*.prefab" or "*.fbx" files and store it in a List / Array.

Now, in a test scenem, i want to instantiate them (using 2 buttons: previous prefab and next prefab).

Using :

```
_currentPrefab = Instantiate ( Resources.Load (prefabs [currentPrefabIndex].ToString(), typeof(GameObject)), SpawnGameObject.transform.position, new Quaternion(0,0,0,0)) as GameObject;

```

Give me an error because (i'm pretty sure) my prefab is outside Resource folder.

So my question is: how can i Instantiate my prefab outside that folder ? Is there a way ?

Thanks

# Answer
> 6 votes
you can loop through your list and instantiate into the hierarchy or a more efficient way would be load in a custom editor window then when you find the one you want you can instantiate into the scene.

you want to load them using either `AssetDatabase` or the `Directory` class. then you can instantiate the result.

```
for int i = 0; i<MyFBXPaths.Length; i ++)
{
    Object _asset;  //each string path would look something like this Assets/YourFolderToAsset/yourasset
    _asset = AssetDatabase.LoadAssetAtPath(MyFBXPaths[i], typeof(Object))
    //edit added Instantiation using your variable for clarity
    _currentPrefab = Instantiate (_asset,SpawnGameObject.transform.position,Quaternion.identity);

}

```

or

```
  var myDirectoryContents = Directory.GetFiles(MyFBXPaths[i] + "/");
            for (int c = 0; c < myDirectoryContents.Length; c++)
            {
               //do stuff

            }

```

to break it down even further to do what you ask all you want is the path. you can easily obtain that for example `Directory.GetFiles("Assets/3dModels/")` will return a array of the paths. a example of loading directly without the array would be

```
_asset = AssetDatabase.LoadAssetAtPath("Assets/3dModels/3dmodel1.prefab", typeof(Object)) as GameObject;
_currentPrefab = Instantiate (_asset,SpawnGameObject.transform.position,Quaternion.identity);

```

both of those classes you can create or manage directories and files within the project without being in the resources folder. Be sure you are `using Unity.Editor` for `AssetDatabase` and or `System.IO` for `Directory`

# Answer
> 2 votes
There are a 2 main ways to instantiate a prefab in Unity.

First, you can have an object in your scene that holds a reference to that prefab. Usually you have a reference to a single prefab you want to load, but you could just as easily have a GameObject array full of all your prefabs. If you want to get fancy about it you could even fill this array procedurally during scene build. When Unity loads the scene, it will loads copies of those prefabs into memory, and you can call instantiate on them.

```
public class Player : MonoBehaviour {
   [SerializeField] private GameObject bulletPrefab;

   public void Fire() {
      var bullet = Instantiate(bulletPrefab);
   }
}

```

The second, and vastly inferior, way is to use resources. Resources, as you discovered, must be in the Resources directory. However, you can load your prefab reference at runtime and instantiate it at runtime. I wouldn't do this often, it's something that would best go in Start.

```
public class Player : MonoBehaviour {
   [SerializeField] private string bulletPrefabPath;
   private GameObject bulletPrefab;

   void Start() {
      bulletPrefab = Resources.Load<GameObject>(bulletPrefabPath);
   }

   public void Fire() {
      var bullet = Instantiate(bulletPrefab);
   }
}

```

There is another way that can be used to some success as well. If you have a set of prefabs that's used across multiple scenes, you can store references to them in a ScriptableObject. A ScriptableObject is like a MonoBehaviour but it exists outside of any scene. Your MonoBehaviours can then have a reference to that ScriptableObject, which holds references to the prefabs. The prefabs will be loaded into memory either when Unity starts, or when a scene starts where one object holds a reference to the ScriptableObject.

```
[CreateAssetMenu(fileName="PrefabCollection", menuName="PrefabCollection")]
public class PrefabHolder : ScriptableObject {
   public GameObject[] prefabs;
}

public class Player : MonoBehaviour {
   [SerializeField] private PrefabHolder bulletPrefabs;

   public void Fire() {
      // Fire a random bullet prefab
      var prefabIdx = Random.Range(0, bulletPrefabs.prefabs.Length - 1;
      var bullet = Instantiate(bulletPrefabs.prefabs[prefabIdx]);
   }
}

```

---
Tags: unity
---


# Question
Title: How can the board fit the screen perfectly in Unity's 2D Roguelike tutorial?
I follow the tutorial 2D Roguelike tutorial. I want to understand how happen that 10x10 board of 32x32 sprites covers screen perfectly? Like what does this depend on?

# Answer
> 8 votes
This depends on several things really.

First is the pixels per unit found in the sprite editor, which determines how many pixels there are for each 1 of Unity's distance units. So if you want your 32x32 sprites to be at 1,1 1,2 ect with no overlap, this should be listed as 32.

Next is the settings on the camera, which show a certain amount of the game world. For a 2d game, Orthographic is probably best. The size setting is what determines how many units the camera displays, being half of the size of the vertical viewing volume (horizontal comes from the aspect ratio).

Finally, there is the scale on the object itself. This is the multiplication of a single run. So if the object is 1 unit long, a scale of 2 would increase it to 2.

On another note, with regards to roguelikes, the more modern way to make them which that tutorial is too old to mention would be a tilemap. In this case, another value to be concerned about would be the cell size, which determines where in the world the tile is placed. A cell size larger than the tiles pixels to units will result in gaps between tiles, and a cell size smaller than the pixels to units will result in overlapping.

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


# Question
Title: How do I test if a circle and concave polygon intersect?
I have a polygon (sometimes convex, but often concave), and a bunch of circles with different radii. How can I find out if a circle is intersecting/overlapping with the polygon?

I could split my concave polygon into convex pieces. Would that help?

# Answer
there are two cases of this problem. First is the intersection and second that is overlaping (containing).

**First (intersection / polygon inside circle):**

Find closest point on every edge of the polygon to the circle's center. If any distance between closest point to the center is less than radius, you got intersection or overlap.

**Second (circle is whole in polygon):** Shoot ray from circle center to the right (or left/up/down) and count ray/segment (polygon edges) intersections. If intersection count is even circle is outside of polygon. If it's odd circle is inside.

I'll share picter from lectue for this case:

And take care of the singular cases.

Hope this will help.

---

edit: I think that it is just fair to add credits to the picture. Author is Petr Felkel, Assistant Professor at Czech Technical University in Prague
> 26 votes

# Answer
The first step, as you guess, is to split the concave polygon into multiple convex ones. The reason for this is that you'll use the separating axis theorem, which only works on convex polygons.

SAT per se only works on two convex polygons. The "separating axis" in the name refers to the axes perpendicular to the edges of the polygon. Circles, unfortunately, have an infinite number of these. However, it turns out there's a pretty easy way to find out which of those axes are relevant, by looking at this which project outwards to intersect the vertices of the polygon.

Rather than go over the entire algorithm here, Metanet Software (makers of N/N+) have a good tutorial on collision detection using SAT, the third section of which covers SAT when one of the objects is a circle.
> 7 votes

# Answer
Here's what I do.

1. Use the horizintal line test to detect if the center of the circle is inside the polygon. If it is, then they intersect.
2. If not, check for the following case. For each side of the polygon
    1. Find the slope of the polygon side
    2. Calculate the Perpendicular Slope
    3. (READ THIS CAREFULLY) Find the intersect between a line with the slope of the polygon side intersecting with either vertex which makes the side, and the line of the slope perpendicular to that of the side which intersects the circle's center.
    4. If the established point of intersection lies inside the circle, this means thee circle at some point crosses over the side in question, and is hence intersecting the polygon
3. Lastly, if nothing else is conclusive, check if any vertices of the polygon lie inside of the circle (because of previous tests, you only need to check once) If so, they intersect. If not, you can conclusively say that they don't.
> 0 votes

---
Tags: collision-detection
---


# Question
Title: How to Subscribe to Events from Unity's VRInput Script
I am new to Unity and trying to modify the Unity tutorial Interactive 360 Sample. I want to be able to call a function when a user swipes using an Oculus Go Controller. I noticed that the VRInput script is included in the project, which seems to be able to detect swipe gestures. But where do I attach that script, and how do I subscribe to the OnSwipe event.

I am currently trying by making an empty game object, and attaching the InputVR script as well as my own script called "GestureHandler" (I'm not sure whether InputVR is already attached to something else in the sample project, or whether I need to attach it at all). In my GestureHandler script I currently have the following:

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

public class GestureHandler : MonoBehaviour {

    void onEnable(){
        VRInput.OnSwipe += HandleSwipe;
    }

    void onDisable(){
        VRInput.OnSwipe -= HandleSwipe;
    }

    void HandleSwipe(){
        Debug.Log("swipe");
    }
}

```

and currently have the following errors:

```
An object reference is required for the non-static field, method, or property 'VRInput.OnSwipe' [Assembly-CSharp]

No overload for 'HandleSwipe' matches delegate 'Action<VRInput.SwipeDirection>' [Assembly-CSharp]

An object reference is required for the non-static field, method, or property 'VRInput.OnSwipe' [Assembly-CSharp]

No overload for 'HandleSwipe' matches delegate 'Action<VRInput.SwipeDirection>' [Assembly-CSharp]

```

# Answer
It is because

1. OnSwipe is not a static event, so you need a reference to a VRInput.
2. OnSwipe's signature receives a VRInput.SwipeDirection.

So it goes like this:

```
using System.Collections;
using UnityEngine;
using VRStandardAssets.Utils;

public class Example : MonoBehaviour
{
    public VRInput input;

    void OnEnable()
    {
        input.OnSwipe += HandleSwipe;
    }

    void OnDisable()
    {
        input.OnSwipe -= HandleSwipe;
    }

    private void HandleSwipe(VRInput.SwipeDirection swipeDirection)
    {
        Debug.Log("Swipe Direction: " + swipeDirection.ToString());
    }
}

```

Hope it helps.
> 0 votes

---
Tags: unity, input, events, virtual-reality, oculus
---


# Question
Title: C++ - How to create an engine editor without frameworks like qt and wxWidgets?
Basically sometimes I like to try to venture into the world of graphics computing, sometimes I have a project or another that uses opengl plus all the "blind" with opengl, I wanted to be able to create an editor like unreal editor or cry editor, basic functionality like dock widgets, buttons etc, and if it can be integrated with the engine, I've tried to create a windows program with WINAPI but God, that's a torture, a lot of code and in the end it's all blind, you end up having to to guess where each element should be, is usually quite limited having practically no legal content about it, on the other hand it was a hand in the wheel for me, very simple indeed, just the way I wanted it, but it does not give me the freedom that I wanted when it comes to computer graphics, I wanted to do something that was my own, without third-party codes (other than libraries like opengl, vulkan and directx of course).

I've been looking at the banshee code but I'm not sure how they did it to create that WINAPI editor, if companies like capcom and others can, then it should not be difficult.

# Answer
If you don't want to use frameworks like qt, wxWidgets, then you'll have to either:

1. Use the platform windowing API (WINAPI, XLib, Cocoa).
2. Write your own widget toolkit and render it yourself using OpenGL/DirectX.

There is no pleasant way around this. (1) is massive pain in the ass. (2) is less pain in the ass, and allows to implement custom game specific widgets easier, but is massive amount of work nevertheless.

What lazy game developers do:

1. Use WinForms + C# and render into a OpenGLControl / DirectX widget.
2. Create small, incomplete IMGUI lib or use existing "Dear Imgui" (with C++).
3. Use Qt, and render into DX/OpenGL widget
4. Use UI tools in engines (Unity has IMGUI).

Or some variations on this.

The times of easy RAD/WYSIWYG UI programming - in the spirit of Delphi - are essentially long gone (WinForms kind of provides similar experience, but is kind of dated).

Looks like Capcom's MT Framework has done (2) - implemented their own widget toolkit (which they render themselves). It doesn't look very pretty (monospaced bitmap fonts!). Excuse the JPG artifacts.

Some first party Sony devs use https://github.com/SonyWWS/ATF. Which is WinForms+C# for UI and C++ engine interop stuff. Not quite pretty either.

There is no easy way.
> 3 votes

---
Tags: c++, architecture, software-engineering, editors
---


# Question
Title: Can I test collision inside an edge collider area in Unity?
I have a triangle with its perimeter represented by an `EdgeCollider2D`, and I want to trigger an event when the player reaches this area.

So I set the collider as a trigger and, I used the OnTriggerStay2D function in my code.

But the event works only when the player is intersecting the line of the collider, not when the player is inside the triangle but not touching the edge.

How can I continue to get OnTriggerStay messages when I'm inside the triangle, not touching the edges?

# Answer
> 1 votes
No, you cannot test collisions inside a region bounded by edge colliders.

An edge collider is just that: an edge. It has no internal area to test with, it's just the edge and nothing but the edge.

To represent a shape with an interior area, you can use a PolygonCollider2D.

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


# Question
Title: Bug with OnColliderEnter/Exit when colliding with multiple objects at almost the same time
Unity Version: 2017.4.1f1

I currently have a game with a jumping mechanic. I only want the jump to work where you're on ground, so I have planes on top of everything, which, if you are on a plane, then you can jump.

This works, however if you are in a position where you are falling and then in quick succession, hit one plane, fall off that plane (like when your centre of mass is hanging off the edge), then land on another plane, at the end of it all, it still thinks you are on the air.

Note: I don't think this is an error with the velocity of the player, at no point do you go through a collider.

So my question is, is there an error in my code (shown below) which I can fix, or should I take another approach towards jumping, thanks. Relevant code below.

```
private bool canJump;
private Rigidbody rb;
public float jumpStrength;

private void OnCollisionEnter(Collision collision)
{
    if (collision.collider.CompareTag("Jumpable"))
    {
        canJump = true;
    }
}
private void OnCollisionExit(Collision collision)
{
    if (collision.collider.CompareTag("Jumpable"))
    {
        canJump = false;
    }
}
private void Update()
{
    if (canJump && Input.GetKey(Keyode.W))
    {
        rb.velocity += new Vector3(0, jumpStrength, 0);
        canJump = false; // Safety measure to ensure consistent jump height
    }
}

```

Thanks

# Answer
> 1 votes
I agree with LinkWindcrafter that a raycast (or larger shapecast) is more likely what you'll want here.

But, if you want to keep using your toggle style, you can rescue it with a small change:

```
private int jumpableCount;
private bool canJump {
    get { return jumpableCount > 0; }
}

private void OnCollisionEnter(Collision collision)
{
    if (collision.collider.CompareTag("Jumpable"))
        jumpableCount++;
}
private void OnCollisionExit(Collision collision)
{
    if (collision.collider.CompareTag("Jumpable"))
        jumpableCount--;
}

```

This way if you touch `JumpableA` (`jumpableCount = 1`) then touch `JumpableB` (`jumpableCount = 2`) and then *stop* touching `JumpableA` (`jumpableCount = 1`), `canJump` is still `true`, because it knows this CollisionExit wasn't your last remaining Jumpable in reach.

# Answer
> 1 votes
It is possible that you have lots of planes on the ground, so you may have entered a plane, and have the flag as true, but you could have also left another plane trigger, even when you were grounded, so it will overwrite the flag to false.

To check ground, a Raycast is almost always used, you could try something like this:

```
private bool canJump;
private Rigidbody rb;
public float jumpStrength;
public float rayLength;

/*private void OnCollisionEnter(Collision collision)
{
    if (collision.collider.CompareTag("Jumpable"))
    {
        canJump = true;
    }
}
private void OnCollisionExit(Collision collision)
{
    if (collision.collider.CompareTag("Jumpable"))
    {
        canJump = false;
    }
}*/

private bool IsGrounded()
{
    RaycastHit hit;

    if(Physics.Raycast(transform.position, Vector3.down, out hit, rayLength))
    {
        if(hit.transform.CompareTag("Jumpable")) return true;
    }

    return false;
}

private void Update()
{
    canJump = IsGrounded();
    if (canJump && Input.GetKey(Keyode.W))
    {
        rb.velocity += new Vector3(0, jumpStrength, 0);
        canJump = false; // Safety measure to ensure consistent jump height
    }
}

```

The **Physics.Raycast** method has a lot of overloads, the one I provided is a basic one. I personally recommend passing LayerMasks as parameter, so you can just detect certain objects with certain layers (example, you could make all your jumpable planes have a custom "Jumpable" layer and pass it as parameter).

hope it helps.

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


# Question
Title: Skeletal animation: unexpected quarternion values
I'm following ThinMatrix's skeletal animation tutorial and his custom written Collada parser is deriving a different rotation quaternion from each keyframe matrix than the Assimp importer library does. They are close, except the values are signed inversely and unpredicatbly.

I dug around his importer code but it's a mess. I assume he is manually performing an additional axis calculation somewhere, any ideas what it could be and why?

Original Matrix

```
1 0 0 0
0 -0.06466547 -0.997907 0
0 0.997907 -0.06466556 3.810999
0 0 0 1

```

Assimp rotation quaternion : `(0.7296115 , 0 , 0 , 0.683862)`

ThinMatrix's rotation quaternion : `-0.72961134 , 0, 0 , 0.68386203)`

And for reference, the position vec3: `(0, 0, 3.810999)`

**Update:**

With an identity matrix both Assimp and the ThinMatrix code produce `(0, 0, 0, 1)`

# Answer
As tkausl suggested, the issue was opposite row/column major matricies. It was problematic because Assimp gives you the position vector and rotation quarternion but does not store the matrix it was derived from, or allow it to be transpose beforehand.

The solution was to manually convert the quarternion back to a matrix, tranpose it, then back to a quarternion, using the following:

```
public Matrix4 QuarternionToRotationMatrix(OpenTK.Quaternion q)
{
    Matrix4 matrix = new Matrix4();
    float xy = q.X * q.Y;
    float xz = q.X * q.Z;
    float xw = q.X * q.W;
    float yz = q.Y * q.Z;
    float yw = q.Y * q.W;
    float zw = q.Z * q.W;
    float xSquared = q.X * q.X;
    float ySquared = q.Y * q.Y;
    float zSquared = q.Z * q.Z;
    matrix.M11 = 1 - 2 * (ySquared + zSquared);
    matrix.M12 = 2 * (xy - zw);
    matrix.M13 = 2 * (xz + yw);
    matrix.M14 = 0;
    matrix.M21 = 2 * (xy + zw);
    matrix.M22 = 1 - 2 * (xSquared + zSquared);
    matrix.M23 = 2 * (yz - xw);
    matrix.M24 = 0;
    matrix.M31 = 2 * (xz - yw);
    matrix.M32 = 2 * (yz + xw);
    matrix.M33 = 1 - 2 * (xSquared + ySquared);
    matrix.M34 = 0;
    matrix.M41 = 0;
    matrix.M42 = 0;
    matrix.M43 = 0;
    matrix.M44 = 1;
    return matrix;
}

public OpenTK.Quaternion QuaternionFromMatrix(Matrix4 matrix)
{
    float w, x, y, z;
    float diagonal = matrix.M11 + matrix.M22 + matrix.M33;
    if (diagonal > 0)
    {
        float w4 = (float)(Math.Sqrt(diagonal + 1f) * 2f);
        w = w4 / 4f;
        x = (matrix.M32 - matrix.M23) / w4;
        y = (matrix.M13 - matrix.M31) / w4;
        z = (matrix.M21 - matrix.M12) / w4;
    }
    else if ((matrix.M11 > matrix.M22) && (matrix.M11 > matrix.M33))
    {
        float x4 = (float)(Math.Sqrt(1f + matrix.M11 - matrix.M22 - matrix.M33) * 2f);
        w = (matrix.M32 - matrix.M23) / x4;
        x = x4 / 4f;
        y = (matrix.M12 + matrix.M21) / x4;
        z = (matrix.M13 + matrix.M31) / x4;
    }
    else if (matrix.M22 > matrix.M33)
    {
        float y4 = (float)(Math.Sqrt(1f + matrix.M22 - matrix.M11 - matrix.M33) * 2f);
        w = (matrix.M13 - matrix.M31) / y4;
        x = (matrix.M12 + matrix.M21) / y4;
        y = y4 / 4f;
        z = (matrix.M23 + matrix.M32) / y4;
    }
    else
    {
        float z4 = (float)(Math.Sqrt(1f + matrix.M33 - matrix.M11 - matrix.M22) * 2f);
        w = (matrix.M21 - matrix.M12) / z4;
        x = (matrix.M13 + matrix.M31) / z4;
        y = (matrix.M23 + matrix.M32) / z4;
        z = z4 / 4f;
    }
    return new OpenTK.Quaternion(x, y, z, w);
}

```
> 1 votes

---
Tags: opengl, skeletal-animation, assimp
---


# Question
Title: How can I make a coroutine run for a specific number of times in Unity?
I use coroutines in unity, with while(true) condition, which runs it indefinitely. I need to make the coroutine run for a specific number of times, let's say 10 times. Any pointers will be much appreciated!

# Answer
Unity Coroutines will exit automatically when they reach the end of the function. Thus, the answer is simply to use a for loop instead of a while loop.

If you need the number of times it runs for to vary, you can pass this in as a function (see this).

For Example:

```
IEnumerator DoSomething(int loops)
{
    for (int idx = 0; idx < loops; idx++)
    {
        print("DoSomething Loop");

        // Yield execution of this coroutine and return to the main loop until next frame
        yield return null;
    }
}

```
> 2 votes

---
Tags: unity, coroutines
---


# Question
Title: Online Browser Game Resource Incrementing Production Problem
I am working on a browser game where there are citys and their resource productions. Each player has their own production rate for each resource.Lets say stone as example. I have production rate,capacity and timestamp(when production started for that resource) for stone in db.I am pulling production rate from db and updating production value on client(incrementing it) but not in db since updating db value each second is not a good idea.So each time user refreshes page or does some action releated to stone,server checks timestamp and production rate and calculates what should be the value of stone in that time,i mean real value and updates client.

```
"stone" : {
        "capacity" : 10,
        "count" : 0,
        "timestamp" : 1531470433, // when production started.
        "rate" : 20, //stone production in a minute
}

```

This calculates users current stone value and updates db.

```
var allStoneProduction= Math.floor((currentTime - stoneDbTime) * stoneProductionRate /60)

```

The problem is with capacity.Players are able to increase capacity of each resource.

I can detect when stone capacity going to be full in server since i know production rate and production start time.Then i am making stonecount equal to capacity.

This code checks if storage is full.If its not it sets value of stone production.

```
var storageFullTime = stoneDbTime+(stoneCapacity/stoneProductionRate)*60

if(currentTime < storageFullTime || currentTime == storageFullTime){
console.log("storage is full!")

Resources.update({ownerId:userid},{$set:{"stone.count":stoneCapacity}})

}else{
Resources.update({ownerId:userid},{$set:{"stone.count":allStoneProduction}})
}

```

As you see allStoneProduction is actually always going up without checking capacity since its only based on rate and start timestamp.This is ok if there is no max capacity.

If stone count reaches its capacity i stop incrementing on client side by checking stonecount,stonecapacity.(10/10) lets say.

If i change capacity from 10 to 20 on db,client gets new capacity value and starts to increment it 11,12,13... until capacity 20.

But server cant follow up this.Should i also write timestamp of when capacity changed ? I couldnt really write the correct if else logic for this.

So how do i compute this capacity change in server side ? `allStoneProduction` value doesnt care about reaching max capacity and increasing capacity.So if change capacity and refresh page,i get a wrong stone count.(since in server logic production never stops)

# Answer
Here's a two-part approach we can use...

When computing current quantity held, we ensure it can never exceed the current capacity:

```
GetCurrentQuantity() {
    return Min(
      capacity,
      storedQuantity + (time - lastStorageUpdateTime) * productionRate
    );
}

```

When incrementing capacity (server-side):

```
ChangeCapacity(newCapacity) {

    currentQuantity = GetCurrentQuantity ();

    if(currentQuantity == capacity) {
        storedQuantity = currentQuantity
        lastStorageUpdateTime = time;
    }

    capacity = newCapacity;
    UpdateDatabase();
}

```

This way, when we increase our capacity (and we need to do a database update anyway to log that change), we bake-out any surplus production that could have leaked through the new cap, and reset the timestamp so further incremental production starts from this moment that the cap changed.

(If we were below capacity at the time of the cap increase, then we don't strictly need to do this, since the result comes out the same either way)

You can do a similar update when logging a spending event or changing the production rate, fixing a new starting point for future increases.
> 1 votes

---
Tags: javascript, databases
---


title: implementing daily challenges in games

text:
# Question
Title: implementing daily challenges in games
I want to know how can I define daily monthly challenges in my game? Is this something can be defined locally or its need server and external services? And which servers and technologies can implements that? Is persistent connection or … needed as server should send messages to clients with no request?

Specifically, I use unity.

# Answer
It all depends how you want to implement them.

Do you want them to be unique every day? Then most likely you'd have to make them in a server, but that adds the negative that users have to be online to get the challenges.

Otherwise you can create something like 100 challenges, and every day give a random one to each user, in which case, you don't need any server and can implement that locally. But in this case, if you want to give new challenges to users, you can only do so through a game update.

How to implement a server that does that? I'm afraid that question is too vague. It takes articles and articles to teach someone that. Basically you'd need a server that stores the data, then the app will attempt to connect to said server and retrieve that data. Assuming you don't want separate challenges for each user, there is no need for authentication, so everyone gets the same challenge every day. How to implement all of these in more detail depends a lot on the current state of your app

---

A few helpful steps for implementation with a server:

* Own a server online (either rent one or if you plan to store low amount of data, you can get away with using something free?)
* Upload a text file that includes information about your challenge. This could be a simple `.txt` file that includes ids of challenges, or a combination of numbers to construct a challenge (pick stage number XX and special rule number YY). Or it could be something more complicated, like a formatted file that includes enough data to define this challenge as precisely as you want (eg `challenge_name = my_challenge; teams = 2; players = 8; ...`). Unfortunately I can't give a more specific example, as both ways can be used for different reasons.
* From your game, at a specific point (when the game starts? when the player presses a button that says "start challenge" ?) make an online connection, that connects to that file on your server.
* If failed, the daily challenge cannot be started (as the game doesn't know what to start)
* If succeed, parse the file, and "create" locally the challenge depending on the data that you retrieved. What data would that be, depends on the variety of your challenges, but it can be a different stage, a different play mode, a specific time limit etc etc

If you are new to something like this, maybe you can try using a json file as you can put abstract information to it, and there are many parsers online so you don't have to do the hard work.
> 4 votes

# Answer
You should really look Asset Bundle on Unity documentation. You'll need a server that can store an asset bundle to do this. Asset bundle are made for the kind of things you want to do, it allows you to download new content from online.
> 1 votes

# Answer
While TomTsagk covered most of the basics in his answer, there are a few other points to think about;

You can use procedural generation to generate challenges. This may have the result in repetitive or boring challenges, however, if implemented badly, or even problems with difficulty (too easy, impossible, ect). Whereas creating by hand will ensure this won't be a problem.

If you want everyone to have the same challenge but would rather not have a server, you can use something like the following to decide which challenge to pick:

```
var rand = new System.Random((int)(DateTime.UtcNow.Date.Ticks >> 10));

```

(Note; not tested this code. May throw a conversion error. The basic idea is to create a local random using todays date in UTC, then use it to choose which challenge to run).

Do you want challenge highscores shared? Then use a server.

A server does not necessarily need be implemented in Unity. In fact, if it does nothing more than serve challenges made by yourself and highscores, Unity is overkill. A restserver can serve just fine. One thing to watch out for is the potential for cheating on the highscores, since you are relying on the client to accurately report them.
> 1 votes

---
Tags: unity, webservice
---


title: Custom Camera View Fustrum in Unity

text:
# Question
Title: Custom Camera View Fustrum in Unity
Is it possible in Unity to make some sort of bounding box (with a running application) within the current viewpoint of the actual screen?

Let me explain:

I'm working on a project which uses a projection for visual output, the screen I am projecting on is smaller than the actual projectors resolution. This means that the unused spaces around the actual working application, are black and visually hidden.

Made an image for exra explanation:

As i'm new to Unity and still learning, I'm not sure if this is even possible because of the use of camera's and environment. I happen to know that it's possible in three.js. But if anyone could point me in the right direction or explain that it's impossible would be much appreciated because I'm not sure where to look anymore!

# Answer
> 3 votes
You can simply set the camera’s Viewport in the inspector. It defaults to x,y,w,h= 0,0,1,1. You could, for example, set it to 0.2,0.1,0.6,0.8

You can include another camera (full screen) that doesn’t render anything but has a clear color of black and has a depth set so it renders before the main camera to ensure you get black around the edges.

The values are relative to the size of the screen (or rather, the game window, if your game is not running in full screen) as a percentage. Taking .5 as an example, as a coordinate (x or y) it refers to the center of the screen, and as a dimension (w or h) it refers to half the screen size.

So for the example above, the values are .2, .1, .6, .8, meaning it is positioned 20% in from the left edge of the screen, taking up 60% of the screen's width. And then the y coordinate starts at 10% from the bottom of the screen, taking up 80% of the screen's height.

If you add up the coordinate and the dimension horizontally (`20% + 60%`) you will get 80%, representing the right edge of the image. Note that `100% - 80% = 20%`, the same as the left edge inset, meaning it is therefore centered on screen horizontally.

The same math applies vertically. `10% + 80% = 90%`, and `100% - 90% = 10%`. If you don't want the image centered, adjust the coordinate and dimension so that `100% - (coordinate + dimension) != coordinate`

# Answer
> 1 votes
Yes, you can do it easily in unity. But first, you need to understand Camera, RenderTexture, Canvas, and RawImage in Unity.

Below is step by step procedure to achieve the result you wanted.

1. Create a New Scene
2. Add New Camera using Right Click \> Camera
3. Change Camera's Projection to "Orthographic" (You can skip this step, or set according to your requirement)
4. Select the "Main Camera" which is by default available in New Scene.
5. Change Camera's Clear Flags to Solid Color and change background to "Black" and change projection to "Orthographic"
6. Create RawImage by Right Click \> UI \> RawImage
7. Now set RawImage Position to the are you want to see ex."Working View"
8. Go to project \> Create \> New RenderTexture
9. Select the RawImage and Drag the RenderTexture you created to RawImage's Texture property.
10. Drag that RenderTexture into the New Camera's "TargetTexture". (Camera we created manually is New Camera)

I hope this helps!

What actually happens here is we transfer Whatever Render into the new camera to "RenderTexture" and make it render back to the scene using RawImage.

---
Tags: unity, camera, projection, viewport
---


# Question
Title: Why in the dialogue system it's showing in the conversation only 2 sentences and not the whole 3 sentences?
The first script the manager is attached to new empty gameobject: I want the conversation to start automatic when running the game so i'm calling the method TriggerDialogue in the manager:

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

public class DialogueManager : MonoBehaviour
{
    public DialogueTrigger dialoguetrigger;

    private Queue<string> sentences;

    // Use this for initialization
    void Start ()
    {
        sentences = new Queue<string>();

        dialoguetrigger.TriggerDialogue();
        DisplayNextSentence();
    }

    public void StartDialogue(Dialogue dialogue)
    {
        Debug.Log("Starting conversation with " + dialogue.name);

        sentences.Clear();

        foreach(string sentence in dialogue.sentences)
        {
            sentences.Enqueue(sentence);
        }

        DisplayNextSentence();
    }

    public void DisplayNextSentence()
    {
        if (sentences.Count == 0)
        {
            EndDialogue();
            return;
        }

        string sentence = sentences.Dequeue();
        Debug.Log(sentence);
    }

    void EndDialogue()
    {
        Debug.Log("End of conversation.");
    }
}

```

Next the DialogueTrigger:

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

public class DialogueTrigger : MonoBehaviour
{
    public Dialogue dialogue;

    public void TriggerDialogue()
    {
        FindObjectOfType<DialogueManager>().StartDialogue(dialogue);
    }
}

```

Last the Dialogue:

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

[System.Serializable]
public class Dialogue
{
    public string name;

    [TextArea(3, 10)]
    public string[] sentences;
}

```

In the editor I filled the all 3 TextAreas each one with a sentence.

Hello world

Hi everyone

I have woke up

When running the game it's showing only to the Hi everyone it's not showing the I have woke up. And it also not showing the "End of conversation." in the log.

# Answer
My solution. and it's working the way I wanted.

I'm using the variable numberofsenteces to help me getting the number of sentences in the class Dialogue. Then I loop over the sentences + 1 since I want to get to the "End of conversation."

In the start I'm calling StartCoroutine(DisplayNextSentenceWithDelay()); Inside DisplayNextSentenceWithDelay I'm looping over the sentences with delay of 2 seconds between each sentence.

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

public class DialogueManager : MonoBehaviour
{
    public DialogueTrigger dialogueTrigger;

    private Queue<string> sentences;
    private int numberofsentences;

    // Use this for initialization
    void Start ()
    {
        sentences = new Queue<string>();
        dialogueTrigger.TriggerDialogue();
        StartCoroutine(DisplayNextSentenceWithDelay());
    }

    public void StartDialogue(Dialogue dialogue)
    {
        Debug.Log("Starting conversation with " + dialogue.name);

        sentences.Clear();
        numberofsentences = dialogue.sentences.Length;

        foreach(string sentence in dialogue.sentences)
        {
            sentences.Enqueue(sentence);
        }

        DisplayNextSentence();
    }

    public void DisplayNextSentence()
    {
        if (sentences.Count == 0)
        {
            EndDialogue();
            return;
        }

        string sentence = sentences.Dequeue();
        Debug.Log(sentence);
    }

    public IEnumerator DisplayNextSentenceWithDelay()
    {
        for (int i = 0; i < numberofsentences + 1; i++)
        {
            yield return new WaitForSeconds(2);
            DisplayNextSentence();
        }
    }

    void EndDialogue()
    {
        Debug.Log("End of conversation.");
    }
}

```
> 0 votes

# Answer
I don't know if that will even count as an answer, but clearly it's better to close this question by flagging it. However, debugging questions are allowed?

Solution: pay attention to when you call `DisplayNextSentence`. You never call it the third time.
> 0 votes

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


# Question
Title: The state that is synced when a window is broken in a FPS game
In order to better understand how state syncing works in games, I wanted to pose a specific example. Say you are in a FPS game with multiple players and someone breaks a window in some building. Wondering what happens in terms of state syncing. For example, there are these aspects:

1. Someone else is watching the player break the window in the game. So it should probably be a real-time update.
2. Someone isn't watching but they hear the sound of the window breaking.
3. Someone is out of range of hearing or seeing the window break, so wondering if it still updates their game world, or it somehow lazily picks up the changes when they go to the area with the broken window.

Wondering how it generally works in these different scenarios. Any FPS game is fine. For example, in (1), if they are sending each individual particle of broken glass over the internet, or somehow they just send the generic action "user x threw object y at window z" and it replays the action on everyone's computer who is watching. In which case somehow the game world is broken up into macro chunks rather than being composed of particles. In (2), maybe they divide the level into zones of seeing and hearing range, and somehow send just the right amount of state then (wondering what kind of state, and how much). Then in (3), if it is lazily picked up, then what sort of queue is kept on the backend. If the data is compressed when it is sent, etc.

# Answer
> 1 votes
I will go over the how state synchronization works, and later will go over your particular cases.

But before that, let me tell you that you do not need to implement all that I say here. If you have a reasonably small number of players, a small map, and your matchmaking won't put together players with bad latency... you can get away with just sending every input to the host, and the host sending global state to everybody.

---

## Prediction and synchronization

The first thing we want is responsiveness. As you know, it is not good to have to wait for the host for every input. Instead, we will send the input commands to the host and simulate/predict locally while waiting for the host. Then, when the host response, we decide if we have to correct the simulation.

Perhaps we have moved beyond the position the host responds, but what we need to check is if we were there - with some margin of error - when we should have been there. That means that the client will have a log of recent states to compare with the host response.

If an enemy makes an stun attack on you, this will be send to the host. The client is not aware of this, but the host is. As a result, the response of the host differs from the local simulation, and we have to make a correction. The client need to resimulate starting from the data recieved from the host. And what is presented to player will - usually - be an interpolation from the wrong simulation to the corrected one, over time.

---

We can improve the simulation quality if we send input data from player to player. That is, if we send input data from your client to the clients of players that are nearby you, they will be able to simulate what your avatar does based on your input.

The key here is to do send this information only for players that are nearby and could see you according to your simulation. That way saving bandwidth in not sending this data to everybody.

---

In some situations, the client will have to waiting for the host to simulate some aspects of the game. That would be in cases where the client needs permision to do an action (as cheat prevention), or can't predict the result of the action on its own.

---

**Notes**:

* There will be discrepancies between client and host, which - for your FPS - means that the player is aiming to a past position, and thus a high latency player could virtually never hit. You have two solutions: 1) extrapolate on the client the future position of the target. 2) Send semantic information about what the player is aiming at to the host. However, in either case, it is up to the host to decide if it hits.
* The host should be aware of latency, and take it into account in any simulation that requires a delay. That is, it should compensate for the lag. Interpolation on the client does not cover all cases of lag compensation.
* There is also host side prediction. for instance, if the player has been advancing, and then there are network problems and we get nothing from the player, the host can asume the player is still doing the same thing.
* Do not wait for the server for windup animations. Let the animation happen on the client as soon as possible after input. In fact, hide the latency in the animations... instead use it for the actual effects. However, wait for the host before you play the animation that notifies the player that the effect has taken place.

---

---

## Managing Bandwidth

Sending notifications of events about everybody to everybody does not scale. It can work for small number of players on a good network, but we do not really know how good the network is.

Thus, we do not want to send notifications to everybody. Instead, we will divide the world in areas. And each player will be subscribed to one or more areas, from which they get notifications.

To be able to send the notifications to players that are out of date, the host will need to have a backlog. However, the hostcan remove the oldest entries to save memory.

Now, given an stream of notification about what happens to the objects in the world, the client should be able to compute the state of the world.

However, if the player did not recieve a large enough number of notification (because the player wasn't subscribed, because the network failed, because the host has removed the entries that it would need to send, or whatever) or if the client has unloaded the object from memory, the host should be able to send the whole state. This can happen when the client reconnects, gets subscribed to a new area, or heuristically on host discretion (in fact, some events may force a whole state update, for example if we need to guarantee that two avatars are in reach for melee).

**Note**: do not let whole state updates eat the bandwidth.

---

## On the structure of network code

The host will have the complete state of the world, and will have it ready to be send to the clients.

However, as said above, the host will not send everything. Thus, we need to decide what to send and what not, and what is the priority for the things that we will send.

Once we have decided to send something to a client, we need to resolve if we are sending notifications of events or whole state updates.

Then we have throttling (to not saturate the network, and also for testing), error handling (for the case of a disconection or time outs), and we monitor latency. And of course, we have to deal with any other low level aspects of whatever network solution we are using.

Remember that we prioritize what to send, if the client only got a few updates, they should have been about the most important parts of the game. Your priorities will be different for every game, however, in general, you want to prioritize updates about what can affect the player, and what the player has done.

---

As long as the client is connected, it should - eventually - recieve the most up to date state of the world. Either by notifications of events, or as whole state updates. And the client will interpolate them.

**Note**: there is no guaraantee that the clients will all the intermediate position, only that they will eventually get the most up to date.

---

## Your Question

> 1. Someone else is watching the player break the window in the game. So it should probably be a real-time update.
> 2. Someone isn't watching but they hear the sound of the window breaking.
> 3. Someone is out of range of hearing or seeing the window break, so wondering if it still updates their game world, or it somehow lazily picks up the changes when they go to the area with the broken window.

1. The host will send the notification of the event to the player watching. And from there, the client will simulate the glass. Futhermore, if you are sending input data among player, that input can arrive early, allowing to predict that the window will be broken.
2. The notification for the player who is not watching will not have a high priority, and thus it can be delayed to allow for more important events. It means that this player could hear the broken window a bit later.
3. Usually, this is the same case as the one above. However, if you have your map divided in areas, and this player is not subscribed to the area where the event happens, there will be no notification at all. Instead it would get a whole state update sometime after getting closer, and will see the window already broken.

> (1), if they are sending each individual particle of broken glass over the internet, or somehow they just send the generic action "user x threw object y at window z" and it replays the action on everyone's computer who is watching. In which case somehow the game world is broken up into macro chunks rather than being composed of particles.

It is up to the game designers to decide if the pieces of glass are only decorative. If they are, then there is no need to synchronize them. However, if they aren't, then the host has to decide on sending this notifications. Each client will simulate them, and correct when they get the notification from the server... It is very likely that they will have very low priority for most players, thus, a high latency player may not get the updates, until the priority goes up (for example an enemy picks up the piece of glass and uses it to try to attack the player).

*I am not sure what you mean by macro chunks, hopefully I covered your question.*

> (2), maybe they divide the level into zones of seeing and hearing range, and somehow send just the right amount of state then (wondering what kind of state, and how much).

This is the state of the art. However it is not true of every game and every map.

> (3), if it is lazily picked up, then what sort of queue is kept on the backend. If the data is compressed when it is sent, etc.

There is a queue of events, to which I refer as the backlog. However, the events are not the truth. The truth is the state of the game in the host. At some point the log will be long enough that it is cheaper to just send the up to date state of objects than to send the log. At that point you should be removing old entries from the log to keep memory requirements of the host in check.

Yes, compresion is used.

---

This answer is based on networking code from Halo: Reach, and Overwatch.

References:

Additional Resources:

---
Tags: first-person-shooter, synchronization, game-state
---


# Question
Title: Is there a way to make collision necessary?
This code I have for my player movement. Now I want to make the player (2d circle) stick to the path. I tried `OncollisionEnter2d` but it's detection wans't an obligation.

```
using UnityEngine;
using System.Collections;

public class player : MonoBehaviour {

    public float speed;

    void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");
        transform.Translate (new Vector2(moveHorizontal,moveVertical)*Time.deltaTime*speed);
    }
}

```

# Answer
> 1 votes
Instead of using colliders to stick to the path, use them to avoid the player to trespass the limit. Add colliders around the path and uncheck `Is Trigger`.

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


# Question
Title: Day/Night cycle with GLSL - blend from one colour to another along Sin curve
I am attempting to implement a day/night cycle using a GLSL fragment shader in a 2D game i'm developing in SFML. I am a novice with shaders with this one being my first.

Currently I am using a lightmap to achieve ambient lighting and spotlights from lightsources (e.g. campfire) which is working nicely. The lightmap shader I am using I got from following an old Alcovegames tutorial, see below:

```
uniform sampler2D texture;
uniform sampler2D lightmap;

uniform vec4 ambient;
uniform vec2 resolution;
uniform int theta;

float PI_180 = 3.141592653589793 / 180;

vec3 ToGlColour3(in vec3 colour)
{
    float dv = (1.0/255);
    return vec3
    (
        dv * colour.r,
        dv * colour.g,
        dv * colour.b
    );
}

vec4 ToGlColour4(in vec4 colour)
{
    return vec4
    (
        ToGlColour3(colour.rgb),
        (1.0/255) * colour.a
    );
}

void main()
{
    vec4 diffuse = texture2D(texture, gl_TexCoord[0].xy);

    vec2 lightcoord = (gl_FragCoord.xy / resolution.xy);
    vec4 light = texture2D(lightmap, lightcoord);

    vec4 ambientLight = ToGlColour4(ambient);

    float ambientIntensity = ambientLight.a * (sin(theta * PI_180) + 0.5);
    vec3 ambientColour = ambientLight.rgb * ambientIntensity;
    vec3 intensity = (ambientColour + light.rgb);

    vec3 result = diffuse.rgb * intensity;

    gl_FragColor = vec4(result, diffuse.a);
}

```

The `ambientIntesity` calculation is my attempt at cycling from night to day. My issue is that it doesn't cycle bright enough to give an adequate daytime effect.

I was thinking I could use the current value of sine(theta) and interpolate from my `ambient` colour to white (representing fully lit daytime).

I'm just not sure how to achieve this in GLSL. Ideally a solution within GLSL would be possible to help develop my knowledge of shaders.

I appreciate any help, Thanks.

# Answer
you are scaling the ambient lighting by a factor of \[-0.5, 1.5\]. Ambient light is generally a small value, because it is meant to add a small amount of light to fragments that would otherwise show up as black due to the lightmap. What you want to do is scale the light.rgb color in the range \[0,n\] where the value of n\*light.rgb is the sunlight at peak daytime.

```
vec3 result = (ambientLight.rgb + n*(sin(...)*0.5+0.5)*light.rgb;

```
> 1 votes

---
Tags: glsl, sfml
---


# Question
Title: Should I avoid using object inheritance as possible to develop a game?
I prefer OOP features when developing games with Unity. I usually create a base class (mostly abstracted) and use object inheritance to share the same functionality to the various other objects.

However, I recently heard from someone that using inheritance must be avoided, and we should use interfaces instead. So I asked why, and he said that "Object inheritance is important of course, but if there are lots of extended objects, relationship between classes are deep coupled.

I'm using an abstract base class, something like `WeaponBase` and creating specific weapon classes like `Shotgun`, `AssaultRifle`, `Machinegun` something like that. There are so many advantages, and one pattern I really enjoy is polymorphism. I can treat the object created by subclasses as though they were the base class, so that the logic can be drastically reduced and made more reusable. If I need to access the fields or methods of the sub-class, I cast back to the sub-class.

I don't want to define same fields, commonly used in different classes, like `AudioSource`/`Rigidbody`/`Animator` and lots of member fields I defined like `fireRate`, `damage`, `range`, `spread` and so on. Also in some cases, some of methods could be overwritten. So I'm using virtual methods in that case, so that basically I can invoke that method using the method from parent class, but if the logic should be different in child, I have manually overridden them.

So, should all these thing be abandoned as bad practices? Should I use interfaces instead?

# Answer
> 67 votes
**Favour composition over inheritance** in your entity and inventory/item systems. This advice tends to apply to game logic structures, when the way in which you can assemble complex things (at runtime) can lead to a lot of different combinations; that's when we prefer composition.

**Favour inheritance over composition** in your application-level logic, everything from UI constructs to services. For example,

`Widget->Button->SpinnerButton` or

`ConnectionManager->TCPConnectionManager` vs `->UDPConnectionManager`.

...there is a clearly defined hierarchy of derivation here, rather than a multitude of potential derivations, so it is just easier to use inheritance.

**Bottom line**: use inheritance where you can, but use composition where you must. P.S. The other reason we may favour composition in entity systems is that there are usually many entities, and inheritance can incur a performance cost to access members on every object; see vtables.

# Answer
> 20 votes
You got a few nice answers already, but the huge elephant in the room in your question is this one:

> heard from someone that using inheritance must be avoided, and we should use interfaces instead

As a rule of thumb, when somebody gives you a rule of thumb, then ignore it. This not only goes for "somebody telling you something", but also for reading stuff on the internet. Unless you know *why* (and can really stand behind it), such advice is worthless and often very harmful.

In my experience, the most important, and helpful concepts in OOP are "low coupling" and "high cohesion" (classes/objects know as little as possible about each other, and each unit is responsible for as few things as possible).

# Low Coupling

This means that any "bundle of stuff" in your code should depend on its surroundings as little as possible. This goes for classes (class design) but also objects (actual implementation), "files" in general (i.e., number of `#include`s per single `.cpp` file, number of `import` per single `.java` file and so on).

A sign that two entities are coupled is that one of them will break (or need to be changed) when the other is changed in any way.

Inheritance increases coupling, obviously; changing the base class changes all subclasses.

Interfaces reduce coupling: by defining a clear, method-based contract, you can change anything about both sides of the interface freely, as long as you don't change the contract. (Note that "interface" is a general concept, the Java `interface` or C++ abstract classes are just implementation details).

# High Cohesion

This means to have each class, object, file etc. be concerned with or responsible for as little as possible. I.e., avoid large classes that do a lot of stuff. In your example, if your weapons have completely separate aspects (ammo, firing behaviour, graphical representation, inventory representation etc.), then you can have different classes that represent exactly one of those things. The main weapon class then transforms into a "holder" of those details; a weapon object then is little more than a few pointers to those details.

In this example, you would make sure that your class representing the "Firing Behaviour" knows as little as humanly possible about the main weapon class. Optimally, nothing at all. This would, for example, mean, that you could give "Firing Behaviour" to *any* object in your world (turrets, volcanoes, NPCs ...) by just a snap of a finger. If you at some point in time want to change how weapons are represented in the inventory, then you can simply do so - only your inventory class knows about that at all.

A sign that an entity is not cohesive is if it grows larger and larger, branching out in several directions at the same time.

Inheritance as you describe it decreases cohesion - your weapon classes are, at the end of the day, big chunks who handle all kinds of different, non-related aspects of your weapons.

Interfaces indirectly increase cohesion by clearly splitting off responsibilities between the two sides of the interface.

# What to do now

There still are no hard and fast rules, all of this is just guidelines. In general, as user TKK mentioned in his answer, inheritance is taught a lot in school and books; it is the fancy stuff about OOP. Interfaces are both probably more boring to teach, and also (if you go past trivial examples) a bit harder, opening up the field of dependency injection, which is not so clear-cut as inheritance.

At the end of the day, your inheritance-based scheme is still better than having no clear OOP design at all. So feel free to stick with it. If you wish to, you can ruminate/google a bit about Low Coupling, High Cohesion and see if you wish to add that kind of thinking to your arsenal. You can always refactor to try that out if you wish to, later; or try out interface-based approaches on your next larger new module of code.

# Answer
> 14 votes
The idea that inheritance must be avoided is simply wrong.

There exists a coding principle called Composition over Inheritance. It says that you can achieve the same things with composition, and it's preferable, because you can reuse some of the code. See Why should I prefer composition over inheritance?

I have to say I like your weapon classes and would it do the same way. But i haven't made a game by now...

As pointed out by James Trotter, composition could have some advantages, especially in the flexibility at runtime to change how the weapon works. This would be possible with inheritance, but it's more difficult.

# Answer
> 6 votes
The problem is that inheritance leads to coupling--your objects need to know more about each other. That's why the rule is "Always favor composition over inheritance". This doesn't mean NEVER use inheritance, it means use it where it's completely appropriate, but if you are ever sitting there thinking "I could do this both ways and they both kind of make sense", just go straight to composition.

Inheritance can also be kind of limiting. You have a "WeaponBase" that can be an AssultRifle--awesome. What happens when you have a double-barrel shotgun and want to allow the barrels to fire independently--a little harder but doable, you just have a single-barrel and double-barrel class, but you can't just mount 2 single barrels on the same gun, can you? Could you mod one to have 3 barrels or do you need a new class for that?

What about an AssultRifle with a GrenadeLauncher underneath--hmm, a little tougher. Can you replace the GrenadeLauncher with a flashlight for nighttime hunting?

Finally, how do you allow your user to make the preceding guns by editing a config file? This is difficult because you've hard-coded relationships that might be better off composed and configured with data.

Multiple inheritance can fix some of these trivial examples somewhat, but it adds it's own set of problems.

Before there were common sayings like "Prefer composition over inheritance", I found this out by writing an overly complex inheritance tree (which was awesome fun and worked perfectly) then finding out that it was really difficult to modify and maintain later. The saying is just so you have an alternative and compact way to learn and remember such a concept without having to go through the whole experience--but if you wish to use inheritance heavily I recommend just keeping an open mind and evaluating how well it works for you--nothing terrible is going to happen if you use inheritance heavily and it might be a great learning experience at worst (at best it might work fine for you)

# Answer
> 3 votes
Contrary to the other answers, this has nothing to do with inheritance vs. composition. Inheritance vs. composition is a decision you make regarding how a class will be implemented. Interfaces vs. classes is a decision that comes before that.

**Interfaces are the first-class citizens of any OOP language.** Classes are secondary implementation details. New programmers' minds are severely warped by teachers and books that introduce classes and inheritance before interfaces.

The key principle is that whenever possible, the types of all method parameters and return values should be interfaces, not classes. This makes your APIs much more flexible and powerful. The vast majority of the time, your methods and their callers should have no reason to know or care about the actual classes of the objects they're dealing with. If your API is agnostic about implementation details, you can freely switch between composition and inheritance without breaking anything.

# Answer
> 2 votes
Whenever someone tells you that one specific approach is the best for all cases, it's the same as telling you that one and the same medicine cures all diseases.

Inheritance vs composition is an is-a vs has-a question. Interfaces are yet another (3rd) way, appropriate for some situations.

Inheritance, or the is-a logic: you use it when the new class is going to behave and be used completely like (outwardly) the old class that you're deriving it from, if the new class is going to expose to the public all the functionality that the old class had... then you inherit.

Composition, or the has-a logic: If the new class just needs to internally use the old class, without exposing the old class' features to the public, then you use composition - that is, have an instance of the old class as a member property or a variable of the new one. (This can be a private property, or protected, or whatever, depending on the use case). The key point here is that this is the use case where you don't want to expose the original class features and use to the public, just use it internally, while in the inheritance case you're exposing them to the public, through the new class. Sometimes you need one approach, and sometimes the other.

Interfaces: Interfaces are for yet another use case - when you want the new class to **partially** and not **completely** implement and expose to the public the functionality of the old one. This lets you have a new class, class from a totally different hierarchy from the old one, behave as the old one in some aspects only.

Let's say that you have assorted creatures represented by classes, and they have functionalities represented by functions. For example, a bird would have Talk(), Fly() and Poop(). Class Duck would inherit from class Bird, implementing all of the features.

Class Fox, obviously, cannot fly. So if you define the ancestor to have all the features, then you could not derive the descendant properly.

If, however, you break the features into groups, representing each group of calls with an interface, say, IFly, containing Takeoff(), FlapWings() and Land(), then you could for the class Fox implement functions from ITalk and IPoop but not IFly. You would then define variables and parameters to accept objects that implement a specific interface, and then the code working with them would know what it can call... and can always query for other interfaces, if it needs to see if other functionalities are also implemented for the current object.

Each of these approaches has use cases when it's the best one, no one approach is an absolute best solution for all cases.

# Answer
> 1 votes
For a game, especially with Unity, which works with an entity-component architecture, you should favor composition over inheritance for your game components. It's much more flexible, and avoids getting into a situation where you want a game entity to "be" two things that are on different leaves of an inheritance tree.

So, for example, say you have a TalkingAI on one branch of an inheritance tree, and VolumetricCloud on another separate branch, and you want a talking cloud. This is hard with a deep inheritance tree. With entity-component, you just create an entity that has a TalkingAI and Cloud components, and you're good to go.

**But** that doesn't mean that in, say, your volumetric cloud implementation, you shouldn't use inheritance. The code for that might be substantial and consist of several classes, and you can use OOP as needed for it. But it will all amount to a single game component.

As a side note, I take some issue with this:

> I usually create a base class (mostly abstracted) and use object inheritance to share the same functionality to the various other objects.

Inheritance is not for code reuse. It's for establishing an *is-a* relationship. A lot of the time these go hand in hand, but you have to be careful. Just because two modules may need to use the same code, it doesn't mean that one is of the same type as the other.

You can use interfaces if you want to, say, have a `List<IWeapon>` with different types of weapons in it. This way, you can inherit from both the IWeapon interface, and the MonoBehaviour subclass for all weapons, and avoid any issues with the absence of multiple inheritance.

# Answer
> -3 votes
You seem to not understand what an interface is or does. It took me about 10+ years of thinking about OO and asking some really smart people questions was I able to have an ah-ha moment with interfaces. Hope this helps.

The best is to use a combination of them. In my OO mind modeling the world and people lets say, some deep example. The soul is interfaced with the body through the mind. The mind IS the interface between the soul (some consider intellect) and the commands it issues to the body. The minds interface to the body is the same for all people, functionally speaking.

The same analogy can be used between the person (body and soul) interfacing with the world. The body is the interface between the mind and the world. Everyone interfaces to the world in the same way, the only uniqueness is HOW we interact with the world, that is how we use our MIND to DECIDE HOW we interface/interact in the world.

An interface is then simply a mechanism to relate your OO structure with another different OO structure with each side having different attributes that must negotiate/map to each other to produce some functional output in a different medium/environment.

So for the mind to call the open-hand function it must implement the interface nervous\_command\_system with THAT having it's own API with instructions how to implement all the requirements necessary before calling open-hand.

---
Tags: unity, architecture, oop
---


# Question
Title: How to dynamically construct a reference to a game object by name
I have game objects tagged MenuOption0, MenuOption1, MenuOption2, etc. I want to keep a currentIndex var, which gets incremented each time the user swipes on the controller. That swipe should increment the currentIndex var, and switch the reference to a new game object, whose text color will be changed.

This is what I'm trying as a test:

```
GameObject testText = GameObject.Find("MenuOption" + 4);
TextMeshProUGUI thisTextMesh = testText.GetComponent<TextMeshProUGUI>();
thisTextMesh.color = colorWhite;

```

How do I dynamically construct a reference to MenuOption1,2,3,4,etc? Or is there a better way to handle this without writing a big long conditional?

# Answer
> 0 votes
Maybe I'm misunderstanding you but if you have a GameObject and Color for each menu option, I would make a custom class to hold the data and then make an array of that class.

For example

```
using UnityEngine;

[System.Serializable]
public class MenuOption
{
    public Color optionColor;
    public GameObject optionPrefab;
}

```

then you can put it into an array, which you can do in the inspector or via code.

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

public class Switcher : MonoBehaviour
{
    public List<MenuOption> options;
    private int optionIndex = 0;

    // Update is called once per frame
    void Update ()
    {
        //
        if (Input.GetKeyDown(KeyCode.A))
        {
            optionIndex += -1;
        }

        if (Input.GetKeyDown(KeyCode.D))
        {
            optionIndex += 1;
        }

        Debug.Log(options[optionIndex].optionColor);
        Debug.Log(options[optionIndex].optionPrefab);
    }
}

```

Make sure you keep the index between 0 and however many options you have, otherwise you will get "Argument is out of range." errors.

---
Tags: unity, c#, scripting, gameobject
---


# Question
Title: Unity c# bullet randomly changes position
i have problem in unity im using this code to shoot bullets and it works but when im shooting bullets are moving left automatically or when i will aim it at right it shoots straight instead i'm using this code right now:

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

public class shootobj : MonoBehaviour {
    public GameObject prefab;

    void Start () {
     prefab = Resources.Load ("projectile") as GameObject;

    }

    void Update () {
        if (Input.GetMouseButtonDown (0)) {
            GameObject projectile = Instantiate (prefab) as GameObject;
            projectile.transform.position = transform.position + Camera.main.transform.forward * 2;
            Rigidbody2D rb = projectile.GetComponent<Rigidbody2D> ();
            rb.velocity = Camera.main.transform.forward * 40;
        }
    }
}

```

what could be causing such thing?

# Answer
**Unexpected Collisions**

Effects like this can happen because the bullet is colliding with something very shortly after spawning - like a piece of your character or gun - or spawning inside another collider. When this happens, the physics engine tries to force the objects apart, which can deflect the bullet off-course.

Using physics layers or `Physics2D.IgnoreCollision` methods, you can ensure the bullet can't hit your character, which prevents most of these unexpected deflections.

**Unexpected Directions**

I notice you're using `Rigidbody2D`, which suggests you're making a 2D game. (This is one of those cases where including a screenshot in your question *really* helps).

In a 2D game, the physics happens in the xy plane. If your camera is looking at the xy plane, then `Camera.main.transform.forward` is pointing along the z axis - perpendicular to the plane of physics. The same goes for the transforms of any sprites or quads visible to the camera - their forward / z axis (the blue arrow in the editor's translation gizmo) points "into" the screen, not along it.

So when you tell the bullet to "go forward" in this sense, it's like if I told you not to go up/down/north/south/east/west, but "go ana" or "increase your spissitude" \- those aren't directions you can go in your three-dimensional physics world!

This means your velocity assignment could end up being a no-op - adding zero velocity, so the only movement imparted on the bullet comes from collision resolution as described above - or if the forward vector is very slightly tilted relative to the xy plane you might get a small nudge in the direction of the tilt.

In 2D, you usually want to work with left & right vectors or up & down, instead of forward/back (which generally point into / out of the screen)
> 1 votes

# Answer
It might be worth setting the angular velocity to zero, before you run rb.velocity. Also i would explicitly state the rotation of each instantiation too. Good luck

```
void Update () {
        if (Input.GetMouseButtonDown (0)) {
            GameObject projectile = Instantiate (prefab) as GameObject;
            projectile.transform.position = transform.position + Camera.main.transform.forward * 2;

            projectile.transform.rotation = transform.rotation + Camera.main.transform.rotation;
            Rigidbody2D rb = projectile.GetComponent<Rigidbody2D> ();

            rB.angularVelocity = Vector3.zero;

            rb.velocity = Camera.main.transform.forward * 40;
        }
    }

```
> 0 votes

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


# Question
Title: Libgdx/Box2D PolygonShape has no position... well, what now?
As my prototype works perfectly fine I want to advance to more fun areas of the project and add a more complex player-character body.

So for Box2D I figured I'd need multiple fixtures, like one for the legs, one for the torso and one for the head.

Each of these fixtures will get a different sprite/texture that should be swappable dynamically if the player puts on some armour or changes cloths etc.

Until now the player-character consisted of a Box2D Body with just **one** single fixture. I added the sprite like this:

```
   body.setUserData(this.sprite);

```

I rendered it like this:

```
 // Draw-method
  if(body.getUserData() != null && body.getUserData() instanceof Sprite) {
      Sprite sprite = (Sprite) body.getUserData();
      sprite.setPosition(body.getPosition().x - sprite.getWidth() / 2, body.getPosition().y - sprite.getHeight() / 2);
      sprite.setRotation(body.getAngle() * MathUtils.radiansToDegrees);
      sprite.draw(spriteBatch);
  }

```

Now that I want to have multiple sprites for different "regions" of the body I figured it's better to add them to the fixture itself. For now I just wanted to reproduce what I already had, so just the **one** sprite I have to the **one** fixture I have right now instead of the body.

I do this like that:

```
Fixture fixture = body.createFixture(fixtureDef);

```

My problem arises when trying to render this.

```
for(Fixture fixture : body.getFixtureList())
{
    if(fixture.getUserData() != null && fixture.getUserData() instanceof Sprite)
    {
        Sprite sprite = (Sprite) fixture.getUserData();
        //sprite.setPosition(fixture.getShape().getPosition() ... // Not gonna work, because PolygonShape has no position! :(
        sprite.draw(spriteBatch);
    }
}

```

As you can read in the comment, the fixture for now has a rectangular shape which is made like:

```
shape = new PolygonShape();
shape.setAsBox(widthInMeters / 2, heightInMeters / 2);

```

The problem is, that a PolygonShape has not position :/ Now when I render this, the sprite is not being drawn at the fixtures position and currently I really have no idea how to fix that.

I'd highly appreciate any help you can give me! Thanks in advance and have a wonderful day! :)

# Answer
A PolygonShape is just a collection of vertices. It's up to you how you want to define which position within that shape is "THE position" of the shape.

* You could for instance use the position of the first vertex.
* Or the centroid / average of all vertices.
* Or the middle (or particular corner) of the bounding box formed from the leftmost, rightmost, topmost, and bottommost vertex positions.

(This bounding box approach will likely be a good match for where your sprite's position is, but of course it depends on how you painted that sprite)

Like a lot of stuff in games, there's not one right answer that the code is supposed to already know. There are many valid choices you as a developer can make, and it's your responsibility to make those choices match consistently between different systems in your game.
> 1 votes

# Answer
This can actually be kind of complicated (perhaps there's a simple way that I've not found yet) so I would suggest letting someone else do it for you. Dermetfan has a really nice utilities library for Box2D and LibGDX which can do exactly what you're asking for.

Add this to your `build.gradle` under `project(:core)` inside `dependencies`

```
project(":core") {
    ...

    dependencies {
        ...
        compile "net.dermetfan.libgdx-utils:libgdx-utils-box2d:0.13.2" // <- This
    }
}

```

Then recompile your gradle project. With this you can replace all of your `Sprite` with `Box2DSprite` which allows you to automatically draw this sprite on a `Body` or `Fixture`.

```
Box2DSprite#draw(batch, fixture);

```

You can also add a `Box2DSprite` to your `Body` or `Fixture`'s user data to automatically draw it.

```
// Set user data to the sprite.
fixture.setUserData(box2DSprite);
// Then we use the -static- function to automatically draw all attached sprites.
Box2DSprite.draw(batch, world);

```

Take a look at this wiki entry for more information.
> 0 votes

---
Tags: java, libgdx, box2d
---


# Question
Title: Combining multiple diffuse textures into one leaves strange distortions?
I made 3 models, each has own material. And after texture painting, I combined each their texture to single textures for optimization.

Currently making Mobile Game with Unity 2018 and using Mobile/BumpedSpecular shader for rendering, which is actually simplified BlinnPhong lighting model.

However after checking the result, I get weird result in some spots with Diffuse texture.

Note that Mobile/BumpedSpecular shader in Unity uses alpha channel of diffuse texture as glossiness. So after I combined those three different diffuse textures, I exported with no background(transparent background) like this:

UV mapped correctly, diffuse texture has alpha, importing alpha channel as well.

Everything seems fine, but why do I have this wrong result? First time I thought that I did something mistake, so I repeated whole process again, but still have same result, not this one, with other models also. So I thought that it was bug from Unity, actually but it wasn't, I tried with Blender and have same result.

So one thing I can know that there might be something missed in my integrated diffuse/glossiness texture. What am I missing?

# Answer
> 1 votes
DMGregory's suggestion to use a different format is simple and straight forward. So perhaps try that first and see if it solves your issue.

However, if you for some reason want to keep using PNG, you can try disable compression or use a plugin like SuperPNG for Photoshop - I can't tell if you're using Photoshop, but it looks like an older version.

Reasons for sticking with PNG can be compatibility with other tools in your pipeline, where formats like TIFF and TGA can sometimes lead to different results depending on the application.

If you're comfortable with command-line tools, ImageMagick may also be an option to convert your file to a PNG.

# Answer
> 1 votes
This often happens when saving in PNG format. As Morten Andersen points out, those streaky stripes are a telltale sign of PNG compression in zero-alpha areas.

The reason is that PNG exporters assume that the alpha channel is transparency, and thus zero-alpha regions will be completely invisible. So, they figure they're free to do whatever weird stuff they want with the colours in those regions in order to get better compression ratios - like extruding stripes of the same colour so adjacent pixels are really easy to predict.

To avoid this, you can save your source assets in a format that does not assume that an alpha channel with a value of zero will be invisible, like TGA "Targa" or PSD itself. Rather than storing the alpha in the transparency of each layer, you'd go into your channels window in Photoshop and paste your gloss map on a new alpha channel.

(This same reason is why Unity has that "alpha is transparency" checkbox on its importer, so it knows how to interpret zero-alpha regions)

These formats tend to be bigger on disc than png, but ultimately your assets get baked to GPU-friendly formats when you build your game anyway, so it shouldn't impact your published game's size or memory footprint.

---
Tags: unity, shaders, textures, texture-atlas, rendertexture
---


# Question
Title: Fastest visibility calculation towards all possible directions
I am searching for your advice. I have a massive voxelized model, like the one in the picture (but with a few million voxels more..). To reduce the total number of the model’s triangulations, I can remove the shared faces among the voxels, nevertheless, the triangles will indeed remain MANY. What I need to do is create an index that will hold a boolean list (of visible/not visible) information, coming from the following procedure:

Define a set of points, like the centroids of the 3 yellow voxels in the picture (but, this set might again contain millions of points) and for each point calculate which voxels (except their corresponding containers) can be seen (direct and unblocked line of site) towards ALL directions (something like a global illumination concept). If the ray-source (coming from a given point) can reach even at the minimum a target voxel, it means we have a "true" condition for that voxel. For example, if we assume that the ray-source point in the picture is the light source, then all voxels in the blue circle are "true" for the specific point.

This has nothing to do with game development, so I am sorry if my post should be somewhere else. I just felt I should better ask here, because most of my searches conclude to ray-casting, hard shadows, visible surface determination, OpenGL, etc which are quite relevant here. I do not need to see any graphics (or have high fps :D), just store the results for future usage into a 3rd simulation process.

I get the feeling that if I go with implementing simply geometric calculations this indexing will run for too long (even though this can be parallelized quite easily I believe). Nonetheless, can I take advantage somehow of OpenGL and GPU maybe? Will this boost significantly my task? How should I approach the problem? I am working on an ASUS ROG-G752VY.

I only have to construct and store this index (which I would not be surprised if it would turn out to be tens of GBytes). The rest of the simulation runs on a cluster continuously. This indexing calculation operation will run more or less only once.

I just don't know what execution time to expect (days/weeks/years) with this amount of ray-source points that I am mentioning along with a "brute" check towards all directions and voxels (with or without the use of OpenGL and GPU). Yet, I can predict that the max number of visible voxels every time will be just a few thousand.

That, because (sorry for not mentioning it) there is a life-termination logic of this ray when the distance of its travel exceeds "x" units ("x" will be much much smaller than the size of the total model). Hence, for a ray further than "x" the searching process should break every time.

Thank you so much already for your time!!!

# Answer
> 1 votes
Minecraft has to solve a similar problem for culling caves and other landscape features that are occluded from view.

There's a detailed write-up here about the Advanced Cave Culling Algorithm they use, which may have some useful inspirations for this problem.

Their algorithm is approximate and conservative (it will err on the side of saying something is visible, even if it really isn't), but something along these lines could be useful as a first broad-phase pass, to thin the number of voxels you need to consider for more precise tests later.

The algorithm works by dividing the world into chunks of 16x16x16 voxels.

For each chunk, they compute whether a ray entering from one face of the chunk could exit through each other face (15 bools). They do this in a conservative way, by checking whether a flood fill starting at one face touches the other faces - so it will report "true" for some configurations that no straight ray could traverse. It works well enough to cull in situations when you have many solid walls/barriers, but if your voxels are more sparsely laid out you might want a more picky test at this stage.

Then they perform a breadth-first search through the grid of connected chunks, searching outward from the viewpoint, to get a list of potentially-visible chunks in front-to-back order (helping subsequent depth ordering early-out faster)

As you can see the results aren't perfect by any means. The method only looks at immediately adjacent chunks, so it can't see that the ravine at the far right is actually occluded by the rise to the left. But it does successfully eliminate much of the interior detail of the subterranean caves.

Subsequent raycasting against the chunk representation might allow further elimination (solving the original problem at a lower level of granularity)

# Answer
> 0 votes
You could assign a different color to each of the voxels, render your scene to a cubemap texture (sevaral times, from each starting point), then copy the texture to RAM and find all unique colors it contains.

---
Tags: opengl, raycasting, computational-geometry, line-of-sight, visibility-determination
---