cocos2d-x的CCAffineTransform相关变换实现原理

前端之家收集整理的这篇文章主要介绍了cocos2d-x的CCAffineTransform相关变换实现原理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

cocos2d-x的CCAffineTransform相关变换实现原理

  稍有opengl或3d基础的都知道平移/旋转/缩放这几个基本模型视图变换的实现原理,最近看了下cocos2d-x相关部分的实现,了解了这些实现那些各种坐标变换基本不在话下了,cocos2d-x本身还是相对简单的引擎.

  1. CCAffineTransform

struct CCAffineTransform {
float a,b,c,d;
float tx,ty;
};
表示变换矩阵:

构造CCAffineTransform结构

CCAffineTransform __CCAffineTransformMake(float a,float b,float c,float d,float tx,float ty)
{
CCAffineTransform t;
t.a = a; t.b = b; t.c = c; t.d = d; t.tx = tx; t.ty = ty;
return t;
}

  1. 单位矩阵

CCAffineTransform CCAffineTransformMakeIdentity()
{
return __CCAffineTransformMake(1.0,0.0,1.0,0.0);
}
将CCAffineTransform构造为单位矩阵:

  1. 平移

CCAffineTransform CCAffineTransformTranslate(const CCAffineTransform& t,float ty)
{
return __CCAffineTransformMake(t.a,t.b,t.c,t.d,t.tx + t.a * tx + t.c * ty,t.ty + t.b * tx + t.d * ty);
}
将CCAffineTransform矩阵和平移矩阵的结果:

  1. 旋转

复制代码
CCAffineTransform CCAffineTransformRotate(const CCAffineTransform& t,float anAngle)
{
float fSin = sin(anAngle);
float fCos = cos(anAngle);

return __CCAffineTransformMake(    t.a * fCos + t.c * fSin,t.b * fCos + t.d * fSin,t.c * fCos - t.a * fSin,t.d * fCos - t.b * fSin,t.tx,t.ty);

}
复制代码
绕Z轴旋转矩阵右乘以变换矩阵:

  1. 缩放

CCAffineTransform CCAffineTransformScale(const CCAffineTransform& t,float sx,float sy)
{
return __CCAffineTransformMake(t.a * sx,t.b * sx,t.c * sy,t.d * sy,t.ty);
}

  1. Concate

复制代码
/* Concatenate t2' tot1’ and return the result:
t’ = t1 * t2 */
CCAffineTransform CCAffineTransformConcat(const CCAffineTransform& t1,const CCAffineTransform& t2)
{
return __CCAffineTransformMake( t1.a * t2.a + t1.b * t2.c,t1.a * t2.b + t1.b * t2.d,//a,b
t1.c * t2.a + t1.d * t2.c,t1.c * t2.b + t1.d * t2.d,//c,d
t1.tx * t2.a + t1.ty * t2.c + t2.tx,//tx
t1.tx * t2.b + t1.ty * t2.d + t2.ty); //ty
}
复制代码

结果相当于t2 . t1

  1. CCPointApplyAffineTransform

复制代码
CCPoint __CCPointApplyAffineTransform(const CCPoint& point,const CCAffineTransform& t)
{
CCPoint p;
p.x = (float)((double)t.a * point.x + (double)t.c * point.y + t.tx);
p.y = (float)((double)t.b * point.x + (double)t.d * point.y + t.ty);
return p;
}
复制代码

  1. CCAffineTransformInvert

复制代码
CCAffineTransform CCAffineTransformInvert(const CCAffineTransform& t)
{
float determinant = 1 / (t.a * t.d - t.b * t.c);

return __CCAffineTransformMake(determinant * t.d,-determinant * t.b,-determinant * t.c,determinant * t.a,determinant * (t.c * t.ty - t.d * t.tx),determinant * (t.b * t.tx - t.a * t.ty) );

} 复制代码 求矩阵的逆矩阵,通过Mathematica计算得:

猜你在找的Cocos2d-x相关文章