Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read objects from left to right

Tags:

c#

unity3d

I wrote a C# Script in Unity, which detects all visible objects. Now I would like to output them from left to right, as how they are positioned in the scene. Each objects has a number and yet the script outputs the objects by ascending order.

My idea:

I thought about a for-loop which goes along the horizontal field of view. First calculating the horizontal FOV by:

private static float horizontalFOV() {
    float radAngle = Camera.main.fieldOfView * Mathf.Deg2Rad;
    float radHFOV = 2 * Mathf.Atan(Mathf.Tan(radAngle / 2) * Camera.main.aspect);
    float hFOV = Mathf.Rad2Deg * radHFOV;

    return hFOV;
}

And creating the loop by:

public static string OutputVisibleRenderers (List<Renderer> renderers) {
    float hFov = horizontalFOV ();

    if (null == renderers)
        throw new System.ArgumentNullException ("renderers are null");

    for (int i = 0; i < hFov; i++) {
        foreach (var renderer in renderers) {
                if (IsVisible (renderer)) {
                myList.Add (renderer.name);
            }
        }
    }
    string itemsInOneLine = string.Join ("-", myList.ToArray());
    myList.Clear ();
    print (itemsInOneLine);
    print ("--------------------------------------------------");
    return itemsInOneLine;
}

But unfortunally this doesn't work. So how could I read all objects from left to right?

like image 781
Viktoria Avatar asked Oct 29 '22 04:10

Viktoria


1 Answers

I don't use Unity, so sorry if I'm missing something, but it seems that although in the outer for loop You look from left to right, You don't use this information inside the loop. The inner loop just checks if each renderer is visible and adds it to the list, so they probably appear in the output list in the order they are put in the renderers collection.

In order to sort the objects from left to right, You should probably calculate their on-screen coordinates and then use them for sorting. To calculate this, You can use Camera.WorldToScreenPoint method. I've found some suggestions that may be helpful here: http://answers.unity3d.com/questions/49943/is-there-an-easy-way-to-get-on-screen-render-size.html.

To sort the objects, You can use SortedList class described here: https://msdn.microsoft.com/en-us/library/ms132319(v=vs.110).aspx. After calculating on-screen coordinates for each object, just add it to the list with on-screen X coordinate as the key and the list will automatically keep the objects ordered.

like image 105
Lukasz M Avatar answered Nov 15 '22 04:11

Lukasz M