# transform.localPosition.y will not go negative

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);
energy = -mu * (2 * semiMajorAxis);
period = 2 * Mathf.PI * Mathf.Sqrt(semiMajorAxis * semiMajorAxis * semiMajorAxis) / (Mathf.Sqrt(mu));
}

6095190–662427–OrbitHandler.cs (1.84 KB)

What’s the point of this line of code?

``````y = Mathf.Sqrt(range * range - x * x);
``````

As far as I can tell this will just return the positive version of what y already was… In other words, you could get the same result by writing:

``````y = Mathf.Abs(y);
``````

For example if x was 3 and y was -4, the range will be 5. But then when you go back and recalculate y like this you will get +4 back out for y since Mathf.Sqrt always returns the positive root. So why does this piece of code even exist? I would simply delete that line.

It seems I must have left it in after doing something other stuff. Deleted! Thank you

It appears that was it. It now can go negative. Thank you

1 Like