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

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.

主站蜘蛛池模板: 东丰县| 潜山县| 磐安县| 临沧市| 奇台县| 修文县| 崇阳县| 呼和浩特市| 应城市| 翁牛特旗| 缙云县| 东城区| 聂荣县| 武鸣县| 南涧| 峡江县| 科技| 贵溪市| 阿拉善盟| 潍坊市| 镇安县| 寿宁县| 安徽省| 定南县| 衡山县| 重庆市| 敖汉旗| 潼南县| 会同县| 丹寨县| 集安市| 阳城县| 寿阳县| 霍城县| 定西市| 琼中| 阜新| 义马市| 普安县| 德江县| 甘洛县|