官术网_书友最值得收藏!

Vector length

Vectors represent a direction and a magnitude; the magnitude of a vector is its length. The formula for finding the length of a vector comes from trigonometry. In the following figure, a two-dimensional vector is broken down into parallel and perpendicular components. Notice how this forms a right triangle, with the vector being the hypotenuse:

Figure 2.5: A vector broken down into parallel and perpendicular components

Figure 2.5: A vector broken down into parallel and perpendicular components

The length of the hypotenuse of a right triangle can be found with the Pythagorean theorem, A2 + B2 = C2. This function extends to three dimensions by simply adding a Z component—X2 + Y2 + Z2 = length2.

You may have noticed a pattern here; the squared length of a vector equals the sum of its components. This could be expressed as a dot product—Length2(A) = dot(A, A):

Important note:

Finding the length of a vector involves a square root operation, which should be avoided when possible. When checking the length of a vector, the check can be done in squared space to avoid the square root. For example, if you wanted to check if the length of vector A is less than 5, that could be expressed as (dot(A, A) < 5 * 5).

  1. To implement the square length function, sum the result of squaring each component of the vector. Implement the lenSq function in vec3.cpp. Don't forget to add the function declaration to vec3.h:

    float lenSq(const vec3& v) {

        return v.x * v.x + v.y * v.y + v.z * v.z;

    }

  2. To implement the length function, take the square root of the result of the square length function. Take care not to call sqrtf with 0. Implement the lenSq function in vec3.cpp. Don't forget to add the function declaration to vec3.h:

    float len(const vec3 &v) {

        float lenSq = v.x * v.x + v.y * v.y + v.z * v.z;

        if (lenSq < VEC3_EPSILON) {

            return 0.0f;

        }

        return sqrtf(lenSq);

    }

    Important note:

    You can find the distance between two vectors by taking the length of the difference between them. For example, float distance = len(vec1 - vec2).

主站蜘蛛池模板: 鸡东县| 万山特区| 全州县| 丰宁| 黄骅市| 阿拉善右旗| 开原市| 东丰县| 鲁甸县| 佛坪县| 甘南县| 华坪县| 新巴尔虎右旗| 通化县| 星子县| 呈贡县| 彭州市| 玉门市| 阜平县| 静宁县| 商城县| 铜川市| 土默特左旗| 山阴县| 霞浦县| 宝山区| 博乐市| 华阴市| 兴安县| 宣城市| 双辽市| 宁蒗| 股票| 当涂县| 青神县| 宁河县| 鹿邑县| 申扎县| 彭阳县| 海淀区| 肇州县|