From 7589d62732b68b99de1bec561b1703dd2b043c03 Mon Sep 17 00:00:00 2001 From: hyzboy Date: Thu, 1 Aug 2024 01:39:33 +0800 Subject: [PATCH] Added GetRotateQuat() --- inc/hgl/math/Matrix.h | 3 ++- src/Math/Matrix4f.cpp | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/inc/hgl/math/Matrix.h b/inc/hgl/math/Matrix.h index e88bc31..bf361fe 100644 --- a/inc/hgl/math/Matrix.h +++ b/inc/hgl/math/Matrix.h @@ -215,7 +215,8 @@ namespace hgl return root*child; } - const Matrix4f GetRotateMatrix(const Vector3f &world_position,const Vector3f &cur_direction,const Vector3f &new_direction); + const Matrix4f GetRotateMatrix(const Vector3f &world_position,const Vector3f &cur_direction,const Vector3f &new_direction); + const Quatf GetRotateQuat(const Vector3f &world_position,const Vector3f &cur_direction,const Vector3f &new_direction); /** * 带误差的比较两个浮点矩阵是否相等 diff --git a/src/Math/Matrix4f.cpp b/src/Math/Matrix4f.cpp index 5da0110..4d58b45 100644 --- a/src/Math/Matrix4f.cpp +++ b/src/Math/Matrix4f.cpp @@ -195,4 +195,21 @@ namespace hgl return glm::rotate(Matrix4f(1.0f),angle,axis); } + + /** + * 计算一个方向旋转成另一个方向的四元数 + */ + const Quatf GetRotateQuat(const Vector3f &world_position,const Vector3f &cur_direction,const Vector3f &new_direction) + { + Vector3f axis=glm::cross(cur_direction,new_direction); + + if(glm::length2(axis)<0.0001) + return Quatf(1.0f,0.0f,0.0f,0.0f); + + axis=glm::normalize(axis); + + float angle=acos(glm::dot(cur_direction,new_direction)); + + return glm::angleAxis(angle,axis); + } }//namespace hgl