在网格生成期间经常需要法向矢量(即,垂直于平面的矢量),此外,法向矢量还可能用于路径跟踪和其他情况。在平面中给定三个点(比如网格三角形的角点),就很容易找到法线。选择三个点中的任意一个点,然后分别从其他两个点减去这个点,即可得到两个矢量:
var a: Vector3;
var b: Vector3;
var c: Vector3;
var side1: Vector3 = b - a;
var side2: Vector3 = c - a;
这两个矢量的差积将得出垂直于表面的第三矢量。使用“左手规则”可确定将这两个矢量传递到叉积函数的顺序。在表面上方从上往下看(法线将指向外部)时,第一个矢量应顺时针扫过第二个矢量:
var perp: Vector3 = Vector3.Cross(side1, side2);
如果输入矢量的顺序颠倒,结果将指向完全相反的方向。
对于网格,法向矢量也必须归一化。可通过归一化属性来实现此目的,但是还有另一个偶尔有用的技巧。还可以将垂直矢量除以其大小,从而将其归一化:
var perpLength = perp.magnitude;
perp /= perpLength;
事实证明,三角形的面积等于 perpLength / 2。如果需要得出整个网格的表面积,或者想要根据相对面积随机选择三角形,这会很有用。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.