Ray中的GetPoint()但具有填充和角度

时间:2019-06-08 20:58:56

标签: c# unity3d 3d

这可能是一个奇怪的问题,但是作为Unity的新手,我不知道该如何解决问题,但是我发现Ray()类是所有工作中最有用的类之一。无论如何,要计算光线的给定点,很容易调用.GetPoint(distance)。 -但是有没有办法进行类似.GetPoint(distance, padding, angle)的通话?

例如,给定从ab的(3D)光线

a--c----b
   |
   d

.GetPoint(3)的调用将返回c,对有用/新方法.GetPoint(3, 2, 0)的调用应返回d。此外,调用.GetPoint(3, 2, 90)应该返回d when it's behind (or above) c

我想我应该在数学课上更加注意...

1 个答案:

答案 0 :(得分:1)

如果您不介意Unity找到任意起点,则可以使用Vector3.OrthoNormalize为您获取起点。

然后,您可以使用Quaternion.AngleAxis绕着射线的方向旋转点(您必须使射线在旋转操作的原点/原点之间偏移)。

Vector3 GetPaddedPoint(Ray ray, float distance, float padding, float angleInDegrees) 
{
    Vector3 rayDirection = ray.direction;
    Vector3 startingOrtho;
    Vector3.OrthoNormalize(ref rayDirection, ref startingOrtho);

    // Find some point padding from ray at distance from origin
    Vector3 axisPoint = ray.GetPoint(distance);
    Vector3 startingPoint = padding * startingOrtho+ axisPoint;

    // Find where startingPoint would be if the origin of the ray was at the origin
    Vector offsetPoint = startingPoint - ray.origin;

    // Rotate the offsetPoint around ray direction using Quaternion
    Quaternion rotation = Quaternion.AngleAxis(angleInDegrees, rayDirection);
    Vector3 rotatedOffsetPoint = rotation * offsetPoint;

    // Add back in the ray's origin
    return rotatedOffsetPoint + ray.origin;

}

如果发现您喜欢特定的方向作为起点,则可以传递startingOrtho。保持OrthoNormalize调用以确保它startingOrtho垂直于射线并归一化(如果尚未射线化)。

Vector3 GetPaddedPoint(Ray ray, float distance, float padding, float angleInDegrees, Vector3 startingOrtho) 
{
    Vector3 rayDirection = ray.direction;
    Vector3.OrthoNormalize(ref rayDirection, ref startingOrtho);

    // Find some point padding from ray at distance from origin
    Vector3 axisPoint = ray.GetPoint(distance);
    Vector3 startingPoint = padding * startingOrtho+ axisPoint;

    // Find where startingPoint would be if the origin of the ray was at the origin
    Vector offsetPoint = startingPoint - ray.origin;

    // Rotate the offsetPoint around ray direction using Quaternion
    Quaternion rotation = Quaternion.AngleAxis(angleInDegrees, rayDirection);
    Vector3 rotatedOffsetPoint = rotation * offsetPoint;

    // Add back in the ray's origin
    return rotatedOffsetPoint + ray.origin;

}