Answer the question
In order to leave comments, you need to log in
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));
}
}
Answer the question
In order to leave comments, you need to log in
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]).
phi1 = phi < 180 ? phi : phi - 360;
theta1 = theta + 90;
phi = phi1 < 0 ? phi1 + 360 : phi1;
theta = theta1 - 90;
float r = sphericalCoordinates.x;
float theta = sphericalCoordinates.y;
float phi = sphericalCoordinates.z;
phi = phi < 0 ? phi + 360 : phi; // впрочем, конкретно эта строка не влияет на результат
theta = theta - 90;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question