大二的时候特意花了几天时间看点积叉乘,时间一久又忘了!!!这一次把之前看的代码和找的资料收集起来,下次再忘了就直接看了!!
叉乘的公式记忆技巧
x1 y1 z1
x2 y2 z2
x:【y1,开始小叉】y:【左上与右下大叉】z:【x1开始,小叉】
叉乘的意义:可以判断方向性,可以算面积
//我们是以A点作为dist的判断点
inline bool LineIntersection2D(Vector2D A,
Vector2D B,
Vector2D C,
Vector2D D,
double& dist,
Vector2D& point)
{
double rTop = (A.y-C.y)*(D.x-C.x)-(A.x-C.x)*(D.y-C.y);
double rBot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x);
double sTop = (A.y-C.y)*(B.x-A.x)-(A.x-C.x)*(B.y-A.y);
double sBot = (B.x-A.x)*(D.y-C.y)-(B.y-A.y)*(D.x-C.x);
//上面4个判断相交性,其实只要最上面两个就可以算出来坐标点了
//下面两个是用来判断相交的
if ( (rBot == 0) || (sBot == 0))
{
//lines are parallel
return false;
}
//cal scal
double r = rTop/rBot;
double s = sTop/sBot;
if( (r > 0) && (r < 1) && (s > 0) && (s < 1) )
{
dist = Vec2DDistance(A,B) * r;
point = A + r * (B - A);
return true;
}
else
{
dist = 0;
return false;
}
}
这是两张推导的图片具体的出处找不到了,写的非常好(如果有时间建议自己推导一下,仿佛像回到中学的时代)(感谢作者)
第一张是算比例的:
算交点的推导
强烈建议跟着推导一下
这个博主写的简单明了,因为怕作者的链接失效截个图保存一下.
代码实现
inline void Vector2D::Reflect(const Vector2D& norm)
{
*this += 2.0 * this->Dot(norm) * norm.GetReverse();
}
反射矩阵的推导
这个花了很多时间去理解逆矩阵的空间变换,ABA.当时觉得这辈子都忘不了结果还是忘了…
以下代码是2d的,所以没有用专门的逆矩阵,如果以后需要用到相关的东西,可以由下面的函数得到启发,3d是4x4的不能这么写!!!
//--------------------- PointToLocalSpace --------------------------------
//
//------------------------------------------------------------------------
inline Vector2D PointToLocalSpace(const Vector2D &point,
Vector2D &AgentHeading,
Vector2D &AgentSide,
Vector2D &AgentPosition)
{
//make a copy of the point
Vector2D TransPoint = point;
//create a transformation matrix
C2DMatrix matTransform;
double Tx = -AgentPosition.Dot(AgentHeading);
double Ty = -AgentPosition.Dot(AgentSide);
//create the transformation matrix
matTransform._11(AgentHeading.x); matTransform._12(AgentSide.x);
matTransform._21(AgentHeading.y); matTransform._22(AgentSide.y);
matTransform._31(Tx); matTransform._32(Ty);
//now transform the vertices
matTransform.TransformVector2Ds(TransPoint);
return TransPoint;
}
//--------------------- VectorToLocalSpace --------------------------------
//
//------------------------------------------------------------------------
inline Vector2D VectorToLocalSpace(const Vector2D &vec,
const Vector2D &AgentHeading,
const Vector2D &AgentSide)
{
//make a copy of the point
Vector2D TransPoint = vec;
//create a transformation matrix
C2DMatrix matTransform;
//create the transformation matrix
matTransform._11(AgentHeading.x); matTransform._12(AgentSide.x);
matTransform._21(AgentHeading.y); matTransform._22(AgentSide.y);
//now transform the vertices
matTransform.TransformVector2Ds(TransPoint);
return TransPoint;
}