- Home /
Steering Separation Behavior: objects move endlessly from center
I'm trying to implement Steering Separation Behavior (following this tutorial) to get a result like this one (and here's also a video of someone going through it, among adjacent concepts)
Basically I have a bunch of rectangles stacked on top of each other and I want to separate them such that they don't overlap. With my code, the rectangles seem to endlessly move away from the center, basically scattering, without stopping, and those that are going in the same direction are still stacked or too close to each other.
Here's what I've tried:
foreach (Transform room in RoomsParentObject.transform)
{
int neighborCount = 0;
Vector2 computeVector = new Vector2();
BoxCollider2D box = room.GetComponent<BoxCollider2D>();
Collider2D[] allColliders = RoomsParentObject.transform.GetComponentsInChildren<Collider2D>();
foreach (Collider2D collider in allColliders)
{
if (collider != box)
{
neighborCount++;
computeVector.x += collider.transform.position.x - room.transform.position.x;
computeVector.y += collider.transform.position.y - room.transform.position.y;
}
}
if (neighborCount != 0)
{
computeVector.x /= neighborCount;
computeVector.y /= neighborCount;
computeVector.x *= -1;
computeVector.y *= -1;
computeVector = computeVector.normalized;
room.transform.position += new Vector3(computeVector.x, computeVector.y, 0).normalized;
}
}
I also tried checking only for rectangles that are directly neighbors of the rectangle im iterating over, with similar results. Any help would be greatly appreciated.
Your answer
Follow this Question
Related Questions
[2D] How to get gameobjects within a tilted rectangle area 0 Answers
How to use Physics2D.OverlapCircleNonAlloc for ground check and jump 0 Answers
How to make a 2D physical movement like this ? 0 Answers
Why is the Unity 2D physics engine only deterministic when Z axis rotation is frozen? 0 Answers
2D paper plane physics 0 Answers