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

Normalizing

A vector with a magnitude of 1 is a normal vector, sometimes called a unit vector. Whenever a vector has a length of 1, we can say that it has unit length. A normal vector is written as the letter of the vector with a caret symbol on top instead of an arrow, Normalizing. We can normalize any vector by dividing each of its components by the length of the vector:

Normalizing

We never implemented division operators for the vector class. We can rewrite the preceding equation as reciprocal multiplication. This means we can obtain the normal of a vector if we multiply that vector by the inverse of its length:

Normalizing

Getting ready

We are going to implement two functions, Normalize and Normalized. The first function will change the input vector to have a length of 1. The second function will not change the input vector; rather it will return a new vector with a length of 1.

How to do it…

Follow these steps to implement functions which will make a vector unit length or return a unit length vector. These steps utilize reciprocal multiplication.

  1. Declare the Normalize and Normalized functions in vectors.h:
    void Normalize(vec2& v);
    void Normalize(vec3& v);
    
    vec2 Normalized(const vec2& v);
    vec3 Normalized(const vec3& v);
  2. Add the implementation of these functions to vectors.cpp:
    void Normalize(vec2& v) {
       v = v * (1.0f / Magnitude(v));
    }
    
    void Normalize(vec3& v) {
       v = v * (1.0f / Magnitude(v));
    }
    
    vec2 Normalized(const vec2& v) {
       return v * (1.0f / Magnitude(v));
    }
    
    vec3 Normalized(const vec3& v) {
       return v * (1.0f / Magnitude(v));
    }

How it works…

Normalizing works by scaling the vector by the inverse of its length. This scale makes the vector have unit length, which is a length of 1. Unit vectors are special as any number multiplied by 1 stays the same number. This makes unit vectors ideal for representing a direction. If a direction has unit length, scaling it by some velocity becomes trivial.

主站蜘蛛池模板: 延庆县| 龙门县| 河东区| 乌兰县| 宿松县| 郓城县| 太湖县| 辽宁省| 平利县| 麟游县| 揭阳市| 恩施市| 平遥县| 平顶山市| 资源县| 怀仁县| 鄂托克旗| 游戏| 阿尔山市| 靖边县| 和平县| 黄山市| 泗水县| 永登县| 阳朔县| 思茅市| 蒙山县| 北安市| 芒康县| 正蓝旗| 澳门| 保靖县| 旅游| 青岛市| 印江| 勐海县| 五大连池市| 邛崃市| 文成县| 靖西县| 方城县|