Tuesday, April 2, 2019

unity - Ensuring that a randomly generated galaxy wont place stars inside one another?



I'm attempting to build a game with a spiral galaxy design. In doing so I followed a short guide on making the rough layout of the galaxy.


My code works, but the "stars" (I'm bad with variable names, in this code "star" refers to the central star of a solar system) often clip into one another. Is there a way for me to ensure that no stars will intersect?


Code below is what I'm using to generate my galaxies.


    for(var i = 0; i < starCount; i++) {
var distance : float = Random.Range(minDistance, maxDistance);
distance = Mathf.Pow(distance, 2);

// Choose an angle betweeen 0 and 2*PI
var angle : float = Random.Range(0.0 , 1.0) * 2 * Mathf.PI;
var armOffset : float = Random.Range(0.0,1.0) * armOffsetMax;


armOffset = armOffset - armOffsetMax/2;
armOffset = armOffset * (1/distance);

var squaredArmOffset : float = Mathf.Pow(armOffset, 2);
if(armOffset < 0) {
squaredArmOffset = squaredArmOffset * -1;
}
armOffset = squaredArmOffset;


var rotation : float = distance * rotationFactor;

angle = Mathf.Round(angle/armSeparationDistance) * armSeparationDistance + armOffset + rotation;

//Convert polar coordinates to 2D cartesian ones
var starX : float = Mathf.Cos(angle) * distance;
var starY : float = Mathf.Sin(angle) * distance;

var randomOffsetX : float = Random.Range(0.0, 1.0) * randomOffsetXY;
var randomOffsetY : float = Random.Range(0.0, 1.0) * randomOffsetXY;


starX += randomOffsetX;
starY += randomOffsetY;

var newStar : Transform = Instantiate(star, Vector3(starX, starY), Quaternion.identity);
newStar.transform.parent = center;
}

Answer



The only way to ensure that is to check previously generated stars coordinates, or make (some of) the variables semi-random, e.g. your angle and radius for next star would constantly grow (radius will reset for next angle of course) for a random value, thus ensuring that no intersection would occur.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...