So here’s a challenging question. I have a Ray generated by two points. Assuming the Ray’s direction is not the same as camera’s forward or backwards direction, how do I get the angle of that ray in respect to a camera?
Here’s a few screenshots demonstrating what I’m trying to do.
I’m attempting to use a two camera setup (one perspective, one orthogonal) to generate a GUI with rotating buttons. The buttons are supposed to point in the direction a transform is at in respect to the character. I’ve tried the following method of “converting” a point in the ray from the perspective camera ( gameCamera
) to orthogonal camera ( guiCamera
), but the results were inconsistent:
Vector3 ConvertPoint(Vector3 gamePoint, Camera gameCamera, Camera guiCamera, float distanceFromGuiCamera)
{
Vector3 viewPortPoint = gameCamera.WorldToViewportPoint(gamePoint);
Ray guiRay = guiCamera.ViewportPointToRay(viewPortPoint);
return guiRay.GetPoint(distanceFromGuiCamera);
}
static float Angle(Vector3 originPoint, Vector3 endPoint)
{
float returnAngle = Mathf.Atan2((endPoint.y - originPoint.y), (endPoint.x - originPoint.x)) * (180f / Mathf.PI);
while(returnAngle > 0f)
{
returnAngle -= 360f;
}
while(returnAngle < 0f)
{
returnAngle += 360f;
}
return returnAngle;
}
public void PositionButton(Camera gameCamera, Camera guiCamera, Ray characterToTransform, float distanceFromGuiCamera,
float nearestDistance, float farthestDistance, float lerpValue, float deltaTime)
{
// Generate 2 points: one at the origin, and one several units away from it
origin = ConvertPoint(characterToTransform.origin, gameCamera, guiCamera, distanceFromGuiCamera);
farthestPoint = characterToTransform.GetPoint(farthestDistance);
farthestPoint = ConvertPoint(farthestPoint, gameCamera, guiCamera, distanceFromGuiCamera);
float angle = Angle(origin, farthestPoint);
Quaternion rotation = Quaternion.Euler(0, 0, angle);
CachedTransform.rotation = rotation;
}
In particular, Vector3 viewPortPoint = gameCamera.WorldToViewportPoint(gamePoint);
has been oddly inaccurate. I don’t know if it has to do with how the gameCamera
is parented to another object for animation, but one odd scenario includes a camera looking in the positive X direction, while the ray is looking in the positive Z-direction (the screenshots above demonstrates this specific scenario). I would normally expect farthestPoint
to be set left of origin
, but instead, I get a farthestPoint
in the right.