8.5.8 修改精灵来使用矩阵
精灵现在有一个平移方法SetPosition,但是它没有类似的SetScale或SetRotation方法。这些方法很有用,结合补间函数使用它们可以得到奇妙的效果,因此有必要添加它们。修改精灵类很简单,但是还需要添加一些额外的成员和方法。
double _scaleX = 1;
double _scaleY = 1;
double _rotation = 0;
double _positionX = 0;
double _positionY = 0;
public void ApplyMatrix(Matrix m)
{
for (int i = 0; i < VertexPositions.Length; i++)
{
VertexPositions[i] *= m;
}
}
public void SetPosition(Vector position)
{
Matrix m = new Matrix();
m.SetTranslation(new Vector(_positionX, _positionY, 0));
ApplyMatrix(m.Inverse());
m.SetTranslation(position);
ApplyMatrix(m);
_positionX = position.X;
_positionY = position.Y;
}
public void SetScale(double x, double y)
{
double oldX = _positionX;
double oldY = _positionY;
SetPosition(0, 0);
Matrix mScale = new Matrix();
mScale.SetScale(new Vector(_scaleX, _scaleY, 1));
mScale = mScale.Inverse();
ApplyMatrix(mScale);
mScale = new Matrix();
mScale.SetScale(new Vector(x, y, 1));
ApplyMatrix(mScale);
SetPosition(oldX, oldY);
_scaleX = x;
_scaleY = y;
}
public void SetRotation(double rotation)
{
double oldX = _positionX;
double oldY = _positionY;
SetPosition(0, 0);
Matrix mRot = new Matrix();
mRot.SetRotate(new Vector(0, 0, 1), _rotation);
ApplyMatrix(mRot.Inverse());
mRot = new Matrix();
mRot.SetRotate(new Vector(0, 0, 1), rotation);
ApplyMatrix(mRot);
SetPosition(oldX, oldY);
_rotation = rotation;
}