0
votes

An example of my code, lets say I have a solar system, center being the sun, this code will spawn all the planets around it randomly with a set radius for each planet, in the Vector3 I change and randomize the X and Z, leaving Y at 0.

This is the code, planetInt is the number of planet in the for loop, 0 being first planet up to the 8 planet.

private float orbitRadius = 3150f;
// Get Radius
float newOrbitRadius = orbitRadius * (planetInt + 1);
// Get Random Positon (here)
Vector3 randomPlanetPosition = new Vector3(Random.insideUnitSphere.x * newOrbitRadius, 0, Random.insideUnitSphere.z * newOrbitRadius);

How would I change the Vector3( X and Z) to be in a specific zone, for example I want all the positions to be in the same area like this picture.

Vector3-zone-picture

How do specify a specific angle like the multiple ones in this image, with Y being 0.

all-zones

1

1 Answers

2
votes

Here is an example:

example of random planets in angle range specified

I created this script:

(I suppose your sun is at the center 0;0;0)

public class NewBehaviourScript : MonoBehaviour
{
    public GameObject PlanetPrefab = null;
    public int numPlanets = 20;
    public float orbitLengthBase = 0.3f;
    public float angleMin = 45f;
    public float angleMax = 120f;

    void Start()
    {
        for (int i = 0; i < numPlanets; i++)
        {
            var newPlanet = Instantiate(PlanetPrefab);
            var randomRotationAngle = Random.Range(angleMin, angleMax);
            var rotation = Quaternion.Euler(0, randomRotationAngle, 0);
            newPlanet.transform.position = rotation * Vector3.right * orbitLengthBase * i;
        }
    }
}

I always assign an arbitrary base vector (here: pointing to the right, (1;0;0)) as the position of the new planet, I multiply it by some factor the change the distance from sun just for the example.

More importantly, I multiply it on the left by a quaternion (math thing to represent a rotation), that I just created with a random Y angle between the max and the min that you want.

You can play with some parameters like angleMax and angleMin to see by yourself.