Below is my code. This is literally my first code. It is a randomly set the position of a spacecraft around a sun. The line y = xy[1] refuses to go negative even if I hard code it to something like -200. The corresponding position once I put it into transform.localPosition is a positive 200. I imagine this is some type of interaction issue between the object and it’s parent as I have to use localPosition instead of position. The solution might be just not have a parent. I checked this by adding a button that calls this calculateRandomPosition function and it never went negative.
public void calculateRandomPosition()
{
// Initialize the orbit to start
Vector2 xy = new Vector2(Random.Range(-400.0f, 400.0f), Random.Range(-400.0f, 400.0f));
x = xy[0];
y = xy[1];
range = Mathf.Sqrt(x * x + y * y);
theta = 180.0f;
y = Mathf.Sqrt(range * range - x * x);
float z = 0.0f;
transform.localPosition = new Vector3(x, y, z);
Vector3 xAxis = new Vector3(1, 0, 0);
offsetAngle = Vector3.Angle(transform.localPosition, xAxis);
eccentricity = Random.Range(0.01f, 0.99f);
angularMomentum = Mathf.Sqrt(range * mu * eccentricity);
semiMajorAxis = angularMomentum * angularMomentum / (mu * (1 - eccentricity * eccentricity));
perigeeRadius = semiMajorAxis * (1 - eccentricity);
apogeeRadius = range;
energy = -mu * (2 * semiMajorAxis);
period = 2 * Mathf.PI * Mathf.Sqrt(semiMajorAxis * semiMajorAxis * semiMajorAxis) / (Mathf.Sqrt(mu));
}
6095190–662427–OrbitHandler.cs (1.84 KB)