public void calculateBounds(
Vector2 parentPosition,
Vector2 position,
Vector2 origin,
Vector2 scale,
float rotation,
float width,
float height)
{
if (rotation == 0f)
{
x = parentPosition.X + position.X - origin.X * scale.X;
y = parentPosition.Y + position.Y - origin.Y * scale.Y;
this.width = width * scale.X;
this.height = height * scale.Y;
}
else
{
// special care for rotated bounds. we need to find our absolute min/max values and create the bounds from that
var worldPosX = parentPosition.X + position.X;
var worldPosY = parentPosition.Y + position.Y;
// set the reference point to world reference taking origin into account
Matrix2D.createTranslation(-worldPosX - origin.X, -worldPosY - origin.Y, out _transformMat);
Matrix2D.createScale(scale.X, scale.Y, out _tempMat); // scale ->
Matrix2D.multiply(ref _transformMat, ref _tempMat, out _transformMat);
Matrix2D.createRotation(rotation, out _tempMat); // rotate ->
Matrix2D.multiply(ref _transformMat, ref _tempMat, out _transformMat);
Matrix2D.createTranslation(worldPosX, worldPosY, out _tempMat); // translate back
Matrix2D.multiply(ref _transformMat, ref _tempMat, out _transformMat);
// TODO: this is a bit silly. we can just leave the worldPos translation in the Matrix and avoid this
// get all four corners in world space
var topLeft = new Vector2(worldPosX, worldPosY);
var topRight = new Vector2(worldPosX + width, worldPosY);
var bottomLeft = new Vector2(worldPosX, worldPosY + height);
var bottomRight = new Vector2(worldPosX + width, worldPosY + height);
// transform the corners into our work space
Vector2Ext.transform(ref topLeft, ref _transformMat, out topLeft);
Vector2Ext.transform(ref topRight, ref _transformMat, out topRight);
Vector2Ext.transform(ref bottomLeft, ref _transformMat, out bottomLeft);
Vector2Ext.transform(ref bottomRight, ref _transformMat, out bottomRight);
// find the min and max values so we can concoct our bounding box
var minX = Mathf.minOf(topLeft.X, bottomRight.X, topRight.X, bottomLeft.X);
var maxX = Mathf.maxOf(topLeft.X, bottomRight.X, topRight.X, bottomLeft.X);
var minY = Mathf.minOf(topLeft.Y, bottomRight.Y, topRight.Y, bottomLeft.Y);
var maxY = Mathf.maxOf(topLeft.Y, bottomRight.Y, topRight.Y, bottomLeft.Y);
location = new Vector2(minX, minY);
this.width = maxX - minX;
this.height = maxY - minY;
}
}