Search code examples
c#unity-game-enginevectorizationadditionarea

Unity/C# Adding two areas represented by two vectors


I have two areas, which are both given in there bounds.size. Now the z-axis doesnt matter for me, since im working in 2D. I want to add these vectors so i have a vector, which represents the jointed area. Simply adding these vectors the normal way does not work. The way the area looks in the end is not important, its just important that the size is the same as, both areas combined.

Edit: I have the bounds.size of two polygoncolliders and i want to get a value that represents the bounds.size of the two polygoncolliders combined

enter image description here

area 1 and area 2 combined


Solution

  • The way the area looks in the end is not important, its just important that the size is the same as, both areas combined.

    As there are nigh infinite possibilities otherwise, I'm going to limit myself to results where x = y, for the simple reason that you don't end up with silly vectors like (0.5,80000) but rather a more balanced (200,200).

    This isn't all that hard when you look at it algebraically:

    float result_area = first_area + second_area;
    

    Calculating the area is easy:

    float area = myVector.X * myVector.Y;
    

    Thus rendering the sum of the areas also easy:

    float result_area = myFirstVector.X * myFirstVector.Y + mySecondVector.X * mySecondVector.Y;
    

    For the sake of example, let's say first_area = 50 and second_area = 350, thus resulting in result_area = 400;

    Since we are limited to results where x = y, the result is the square root of the area:

    float theSquareRoot = Math.Sqrt(result_area);
    myResultVector.X = theSquareRoot;
    myResultVector.Y = theSquareRoot;
    

    As I said, there are many other possible result vectors. For other cases, you're either going to have to define a given ratio (e.g. a ratio of 1 : 4 would give you (10,40) for the same example), but the calculation is a bit harder and you mentioned that you don't care about the exact shape anyway.

    You could also just make a vector where X = result_area and Y = 1 (or vice versa), without having to calculate a square root.


    Note that you've overengineered it. The area of an object is a onedimensional value (a number); yet you're expressing it using a twodimensional value (a number pair) to represent them.
    Since you don't care about particular X/Y values, only what their product is, I would suggest you avoid vectors where possible, so you don't make it unnecessarily complicated.