- Home /
Spawn GameObjects randomly on a Circle Collider2D
Hey guys, how can I spawn gameObjects on a Circle with Circle Collider2D so that the gameObjects also have automatically the right rotation?
Here is an example what I mean:
So the spike should spawn randomly on the circle with the right rotation.
Answer by Hellium · Aug 08, 2015 at 09:03 PM
I am not familiar with 2D games, but here is the idea :
//Drag & drop your circle from the inspector
public CircleCollider2D Circle ;
public void PlaceGameObject( GameObject gameObject )
{
float angle = Random.value * 360 ;
gameObject.transform.position = Circle.gameObject.transform.position + Circle.offset + // Center of the collider
Vector3.right * Circle.radius * Mathf.cos( angle ) + // Horizontal position
Vector3.up * Circle.radius * Mathf.sin( angle ) ; // Vertical position
gameObject.transform.rotation.SetLookRotation( Vector3.forward, gameObject.transform.position - (Circle.gameObject.transform.position + Circle.offset) ); // Try -Vector3.forward if Vector3.forward doesn't work
}
Thank you very much, this is exactly what I was looking for.
But the script has some errors. Operator +' cannot be applied to operands of type
UnityEngine.Vector3' and `float'. Could you help me out?
Oops, indeed ! I have forgotten the unit vectors.
I edited the answer.
Thank you, now I have just one error left: An object reference is required to access non-static member `UnityEngine.Quaternion.SetLookRotation(UnityEngine.Vector3)'. Do you have an idea how to solve that?
Argh, I thought Quaternion.SetLookRotation returned a Quaternion. $$anonymous$$y bad, I edited the answer again ! Sorry for the inconvenience !
Your answer
Follow this Question
Related Questions
How to change the rotation of the circle spawn? 1 Answer
Why does inside unit circle use the world point? 2 Answers
Random Coordinates Outside a Circle 1 Answer
random.onUnitCircle ? 6 Answers