M
M
MyOnAsSalat2018-01-23 20:59:07
Mathematics
MyOnAsSalat, 2018-01-23 20:59:07

How to correctly convert to spherical coordinates?

Hello everyone, I have a question about converting Cartesian coordinates to spherical and vice versa. I looked through the formulas on Wikipedia, asked around in the chat.
I made a converter:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public static class SphericalConverter
{
    public static Vector3 CartesianToSpherical(Vector3 cartesianCoordinates)
    {
        float x = cartesianCoordinates.x;
        float y = cartesianCoordinates.y;
        float z = cartesianCoordinates.z;
        return new Vector3(Mathf.Sqrt(x*x+y*y+z*z),Mathf.Acos(z/ Mathf.Sqrt(x * x + y * y + z * z)),  Mathf.Atan2(y,x));
    }
    public static Vector3 SphericalToCartesian(Vector3 sphericalCoordinates)
    {
        float r = sphericalCoordinates.x;
        float theta = sphericalCoordinates.y;
        float phi = sphericalCoordinates.z;
        return new Vector3(r * Mathf.Sin(theta) * Mathf.Cos(phi), r * Mathf.Sin(theta) * Mathf.Sin(phi), r * Mathf.Cos(theta));
    }

}

I checked that they work by taking the coordinates of the point and running back and forth through both functions, I got the same point,
but the spherical coordinates are not set according to ISO (phi[0 to 360] theta [-90 to 90]), but in a different representation (phi[ 0-180] theta [-180 to 180]).
The translation is needed exactly by the user who sets the spherical coordinates, and for calculating the lengths of segments / areas.
Please tell me how to fix the code to such coordinates.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
youngmysteriouslight, 2018-01-23
@youngmysteriouslight

spherical coordinates are specified not in ISO (phi[0 to 360] theta [-90 to 90]), but in a different representation (phi[0-180] theta [-180 to 180]).

Surely the corners are not reversed? So the range for one of them (longitude) should be 360, for the other (latitude) 180.
If you swap it, that is, in one case, the longitude is from 0 to 360 and the latitude is from -90 to 90, and in the other, the longitude is from -180 to 180 and latitude from 0 to 180, then you need to add a transform
phi1 = phi < 180 ? phi : phi - 360;
theta1 = theta + 90;

where (phi,theta) is in ISO and (phi1,theta1) is in user format. The inverse transformation is written out similarly:
phi = phi1 < 0 ? phi1 + 360 : phi1;
theta = theta1 - 90;

Let's say you want SphericalToCartesian to interpret the input phi,theta in a custom format. You write
float r = sphericalCoordinates.x;
        float theta = sphericalCoordinates.y;
        float phi = sphericalCoordinates.z;
        phi = phi < 0 ? phi + 360 : phi; // впрочем, конкретно эта строка не влияет на результат
        theta = theta - 90;

Similarly for the other transformation.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question