- Home /
Rotate object as long as it's colliding
I'm creating a worldmap filled with pins/icons. This map is quite busy and to avoid pins being piled on top of each other, I'd like to rotate them so that in the end no pin is colliding with another.
Like this:
I reset the rotation back to (0,0,0) every time the user zooms in or out. So the rotation of all items should start over again.
But I can't find a way on how to do it properly.
I tried keeping a list of all collisions using OnTriggerEnter2D/OnTriggerExit2D. And then when the user scrolls I go through a custom method SetRotation:
private void SetRotation()
{
transform.rotation = Quaternion.Euler(0, 0, 0);
int tries = 5;
while (collisions.Count > 0 && tries > 0)
{
if (collisions.All(a => a.transform.position.x <= transform.position.x))
{
transform.rotation = Quaternion.Euler(0, 0, transform.rotation.z - 5);
}
else if (collisions.All(a => a.transform.position.x >= transform.position.x))
{
transform.rotation = Quaternion.Euler(0, 0, transform.rotation.z + 5);
}
tries--;
}
}
The problem with this is that not all collisions are detected for some reason. And it only performs the rotation once, even though it should keep on rotating further to make it collision free.
Then I tried OnTriggerStay2D:
private void OnTriggerStay2D(Collider2D collision)
{
while(RotationTries > 0)
{
if(collision.transform.position.x <= transform.position.x)
{
transform.rotation = Quaternion.Euler(0, 0, transform.rotation.z - 5);
}
else if(collision.transform.position.x >= transform.position.x)
{
transform.rotation = Quaternion.Euler(0, 0, transform.rotation.z + 5);
}
RotationTries--;
}
}
In this case all collisions get detected. (as far as I've seen so far). But still it only rotates items by 5° even though it needs more.
I use a limit of 5 tries for now, so it doesn't get stuck in an endless loop. I'll edit the maximum amount of tries later to get a better result.
Any thoughts on how I can make this work properly?
Why do you use a while() loop in the OnTriggerStay2D() function? Try to remove it, so the function will execute once per frame if it is necessary.
I removed the while() loop. thanks for pointing that out.
While debugging I found out the transform.rotation.z - 5 is rarely executed, and if it is, it's often reset to 0 on its next run. Though the debugger never hits the reset I implemented. (unless it has to)
I vaguely remember this Euler can't go below 0. I'm now solving it differently. Thanks!
Your answer
Follow this Question
Related Questions
Camera bounce back? 0 Answers
Changing layers affect triggers? 1 Answer
Adds too many points to the score? 0 Answers
Rigidbody2D.velocity out of controll 3 Answers
How to fix the position of a character when grabbing a rope? 1 Answer