Search Unity

Center of Multiple Game Objects

Discussion in 'Scripting' started by DeemBabbu, Jun 19, 2020.

  1. DeemBabbu

    DeemBabbu

    Joined:
    Jul 18, 2019
    Posts:
    26
    Code (CSharp):
    1. var centroid = character.transform.position;
    2.         List<Vector3> positions = new List<Vector3>();
    3.         if (transform.root.gameObject == transform.gameObject)
    4.         {
    5.             foreach (var child in objects)
    6.             {
    7.                 centroid += child.position;
    8.                 positions.Add(child.position);
    9.             }
    10.             centroid /= (objects.Count);
    11.         }


    This is my code of getting the center of multiple Gameobjects but it's not returning exact center point. How I can achieve this. Any Help?
     
  2. mbaske

    mbaske

    Joined:
    Dec 31, 2017
    Posts:
    473
    Try centroid /= (float)objects.Count;
     
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Which objects? Currently you're including the position of "character" alongside some collection called "objects". Assuming you want the character's position to be included, your division should be by objects.Count + 1 because your character position is in the mix too.

    Otherwise start the Vector3 at Vector3.zero to stop skewing the result by the character position.
     
  4. DeemBabbu

    DeemBabbu

    Joined:
    Jul 18, 2019
    Posts:
    26
  5. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    For the purposes of this calculation it's just another object. If you are including it, you need to add 1 to your divisor.
     
  6. DeemBabbu

    DeemBabbu

    Joined:
    Jul 18, 2019
    Posts:
    26
    @PraetorBlue But when I change its position as we know the child move accordingly but I don't want to do that. I just want to move Parent and child will remain in same position. How I can achieve that ?
     
  7. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    One simple way to accomplish this is to set the parent of all the children to null, move the parent, then set the parent back.

    But what does this have to do with the problem of calculating a centroid?
     
  8. DeemBabbu

    DeemBabbu

    Joined:
    Jul 18, 2019
    Posts:
    26
    @PraetorBlue Basically "character" is the parent of multiple objects with some de-active game objects. The pivot of character is overall centroid according to children. but I want to calculate it according to only active game objects.
     
  9. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Why are you including the parent in the centroid calculation then? It shouldn't be there, and is skewing your result. Initialize your centroid as Vector3.zero instead of the parent position.
     
    FlightOfOne likes this.