Search Unity

Calculate unoccupied area in Unity C#

Discussion in 'Scripting' started by Cellenseres, Nov 14, 2019.

  1. Cellenseres

    Cellenseres

    Joined:
    Mar 30, 2015
    Posts:
    68
    Hey Guys,

    I'm working on something and I am kinda stuck right now.
    I want to calculate the free area in % of a specific area.
    upload_2019-11-14_10-20-6.png
    GameObject 0 (Plane) => The object I want to calculate the free/unused area on.
    GameObject1 - 3 (cylinders) => occupied area.

    Any idea how I can calculate the free area on GameObject0 via C# Script?


    Thank you in advance
     
  2. jvo3dc

    jvo3dc

    Joined:
    Oct 11, 2013
    Posts:
    1,520
    Actually calculating it based on rectangles and circles is possible, but sounds like a programming contest exercise.

    What you probably want to do is to approximate it. This can be done fairly easily using raycasts. Imagine dividing GameObject 0 into a number of squares. Pretty much like projecting a grid on it.

    Then if you determine whether each square is free or not you have a pretty good approximation to the actual % of free space. Determining whether a square is free can be done with a simple raycast in the middle of the square. If you hit GameObject 0, it's free, else it's not.

    Of course the approximation gets better if you make the squares smaller, but the amount of time needed for the raycasts also increments.

    An in between approach would be to divide GameObject 0 into lines. Then for each line you determine where the line enters and exits each blocking circle. This is still an approximation, but faster and more precise. You will need to calculate some line circle intersections, but that is relatively easy.

    So, for who finds this in the future, there are 3 approaches:

    1. Full calculation
    • Requires multiple intersections between circles and rectangles
    • By far the most complicated to implement, a serious challenge
    • Fastest and 100% accurate
    2. Approximation in strips
    • Requires line with circle intersections
    • Fairly easy to implement
    • Average speed and accuracy
    3. Approximation in squares
    • Only requires a simple RayCast
    • Easiest to implement
    • Slowest and least accurate
    I would recommend option 2 if possible with option 3 as a fallback.
     
    Last edited: Nov 14, 2019