I am trying to develop a game in Unity where you jump from 2D planet to 2D planet, each with its own gravitational pull (The game is 2.5D, technically, but all movement is along the X and Y axes). I would like to place landmines at random points along these planets using the parametric formula; this is the script that I've developed to attach them to the parent Planet object. However, mines are not appearing at the surface of the circles as expected, and are instead appearing very distorted in shape. What might I be doing wrong?
public class LandMine : MonoBehaviour
{
public GameObject mine;
private GameObject landmine;
private System.Random rand;
private Vector3 pos;
List<GameObject> mines;
public void Start()
{
mines = new List<GameObject>();
LevelStart();
}
public Vector3 ran()
{
rand = new System.Random(359);
float angle = rand.Next();
float value = angle * (Mathf.PI/180f);
float x = (float) (0.5000001 * Mathf.Cos(value)) + 6;
float y = (float) (0.5000001 * Mathf.Sin(value)) - 9;
return new Vector3(x,y,0);
}
void LevelStart()
{
for (int i = 0; i < 5; i++)
{
pos = ran;
mine = Instantiate(mine, pos,Quaternion.identity) as GameObject;
mines.Add(mines);
}
foreach (GameObject m in mines)
{
m.transform.parent = this.transform;
}
}
}
The parameter you pass to the Random constructor is the random seed, not the range of numbers. If you want to generate new random numbers each time you start the game, use the parameter-less constructor. Also, declare the random number generator only once. It uses the time clock in order to initialize itself, but since the clock ticks very slowly (compared to the CPU clock frequency) it could generate the same random number several times if you create a new instance each time.
static readonly Random random = new Random();
Then generate a new angle with
int angle = random.Next(360); // generates numbers in the range 0 ... 359
or
double angle = 2.0 * Math.PI * random.NextDouble();
The formulas for the mine coordinates are
mineX = centerX + radius * cos(angle)
mineY = centerY + radius * sin(angle)
Just a note for anyone coming here looking to get a random point inside a circle specifically in Unity:
I don't know if it existed when this was first posted, but you can use UnityEngine.Random.insideUnitCircle()
to get a random point inside a circle with a radius of 1. There's also an insideUnitSphere for getting a random point in a 3D sphere.
Hope that helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With