如何获得球体的法向量?

时间:2012-02-23 14:46:35

标签: raycasting

我必须实现简单的光线跟踪算法,但我无法弄清楚如何获得球体的法向量如果我有球体的原点和半径以及光线的方向。 谢谢 Wiki aboute sphere但我无法理解这个

1 个答案:

答案 0 :(得分:0)

我找到了解决方案:这是C#中的代码:

Double alpha = Math.Asin(sphere.Radius / (Math.Sqrt(Math.Pow(sphere.Origin.X-ray.Origin.X,2)+Math.Pow(sphere.Origin.Y-ray.Origin.Y,2)+Math.Pow(sphere.Origin.Z-ray.Origin.Z,2))));
Double beta = Math.Acos((ray.Direction * (sphere.Origin - ray.Origin)) / (ray.Direction.Length * (sphere.Origin - ray.Origin).Length));

ray.HitParam = VypA(sphere.Origin - ray.Origin, beta, sphere.Radius) / ray.Direction.Length;
Vector4 g = ray.Origin + ray.Direction * ray.HitParam;
ray.HitNormal = (g - sphere.Origin).Normalized;

////the VypA function

    public static Double VypA(Vector4 b, Double beta, Double radius)
            {
                return b.Length * (Math.Cos(beta) - Math.Sqrt(((radius * radius) / (b.Length2) - (Math.Sin(beta) * (Math.Sin(beta))))));
            }