- Home /
move multiple 2d items in a circle around a fixed point
I'm trying to move some objects around a center object in a queue. I tried this solution at it works great for one object, thanks to heads up from this answer:
public class RotateAround : MonoBehaviour {
public float RotateSpeed = 5f;
public float Radius = 1f;
public Transform Target;
private Vector2 _centre;
private float _angle;
private void Start()
{
_centre = Target.position;
}
private void Update()
{
_angle += RotateSpeed * Time.deltaTime;
var offset = new Vector2(Mathf.Sin(_angle), Mathf.Cos(_angle)) * Radius;
transform.position = _centre + offset;
}
}
As I said it works great for one object. But if I try to use it for multiple objects, they just go on top of each other. I tried some ways to solve the issue but failed.
How can I edit this so that I can set a new offset
for each object?
Thank you.
Answer by alexjolig · Apr 25, 2018 at 08:42 AM
I fix the issue by adding a public Range
and use it to set angle in Start
method like this:
[Range(-3.14f, 3.14f)] public float AngleRange;
private void Start()
{
_centre = Target.position;
_angle = AngleRange;
}
Then I set proper values for each items.
Thanks to @Captain_Pineapple for the idea!
Answer by Captain_Pineapple · Apr 25, 2018 at 08:13 AM
Hey there,
simply add a different start value for the variable _angle. For example add the line:
_angle = Random.Range(-3.14f,3.14f);
to your Start() function. This randomizes your startangle and thus your starting position.
Edit:
I missed the queue part in your question... This is something that you should do in a script that is instantiating your rotating objects. Simply divide the full circle by the amount of objects you want to rotate and set these as the starting angles of your objects. Something like the following:
int amountOfObjects = 10;
float fullCircle = 2.0f* 3.141f;
float angleBetweenObjects = fullCircle/amountOfObjects;
for(int i=0;i< amountOfObjects;i++)
{
ListOfYourObjects[i]._angle = i* angleBetweenObjects;
}
It dosn't make a queue, some object will cover others this way.