A way of doing matrix transformations on a Transform2D
Problem to solve
Currently it seems you cannot modify the matrix of a transform because each transformation resets the matrix. In our case we have a grid that consists of tiles that we want to transform with a matrix. This is currently in the Transform2D
/// The total transformation matrix for the component. This matrix combines
/// translation, rotation, reflection and scale transforms into a single
/// entity. The matrix is cached and gets recalculated only as necessary.
///
/// The returned matrix must not be modified by the user.
Matrix4 get transformMatrix {
if (_recalculate) {
// The transforms below are equivalent to:
// _transformMatrix = Matrix4.identity()
// .. translate(_position.x, _position.y)
// .. rotateZ(_angle)
// .. scale(_scale.x, _scale.y, 1)
// .. translate(_offset.x, _offset.y);
final m = _transformMatrix.storage;
final cosA = math.cos(_angle);
final sinA = math.sin(_angle);
m[0] = cosA * _scale.x;
m[1] = sinA * _scale.x;
m[4] = -sinA * _scale.y;
m[5] = cosA * _scale.y;
m[12] = _position.x + m[0] * _offset.x + m[4] * _offset.y;
m[13] = _position.y + m[1] * _offset.x + m[5] * _offset.y;
_recalculate = false;
}
return _transformMatrix;
}
Proposal
I'm not sure how it works exactly but I would like to see maybe a setter for the matrix that either updates the position, scale and rotation so it will work with recalculation or during recalculation the previous matrix should not be overridden.
This is also posted on Stackoverflow if anyone wants more context.
And here is no way to set skew property from PositionComponent.
And here is no way to set
skewproperty from PositionComponent.
This is unrelated to this issue, you can open a separate issue for it if you want.
If there are more people asking for skew we'll add that too, but you are actually the first one. :slightly_smiling_face:
You can perform a skew manually until then by overriding render and calling canvas.skew.
Currently Transform2D is a combination of a translation, rotation and scaling. Crucially, there are many places in the code where we rely on this fact, the code that would work incorrectly if transform allowed skews or non-Z rotations, or anything else custom.
I would suggest not to add any such extra functionality to Transform2D -- it would be more error-prone and less efficient than the current implementation. If really needed, a new class Transform3D can be created to handle such advanced cases.