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

The angle between vectors

If two vectors are of unit length, the angle between them is the cosine of their dot product:

If the two vectors are not normalized, the dot product needs to be divided by the product of the length of both vectors:

To find the actual angle, not just the cosine of it, we need to take the inverse of the cosine on both sides, which is the arccosine function:

Implement the angle function in vec3.cpp. Don't forget to add the function declaration to vec3.h:

float angle(const vec3 &l, const vec3 &r) {

    float sqMagL = l.x * l.x + l.y * l.y + l.z * l.z;

    float sqMagR = r.x * r.x + r.y * r.y + r.z * r.z;

    if (sqMagL<VEC3_EPSILON || sqMagR<VEC3_EPSILON) {

        return 0.0f;

    }

    float dot = l.x * r.x + l.y * r.y + l.z * r.z;

    float len = sqrtf(sqMagL) * sqrtf(sqMagR);

    return acosf(dot / len);

}

Important note:

The acosf function returns angles in radians. To convert radians to degrees, multiply by 57.2958f. To convert degrees to radians, multiply by 0.0174533f.

主站蜘蛛池模板: 茶陵县| 合阳县| 江津市| 开化县| 彰化市| 台山市| 祁阳县| 固安县| 荔浦县| 土默特左旗| 德兴市| 环江| 海城市| 桂东县| 岫岩| 淮阳县| 温宿县| 青田县| 义乌市| 普定县| 集安市| 永修县| 文昌市| 康马县| 富裕县| 平顺县| 诸城市| 满城县| 黎城县| 天水市| 大兴区| 崇礼县| 乌审旗| 朝阳县| 襄汾县| 布拖县| 永顺县| 永清县| 新邵县| 肃南| 沾化县|