I can’t seem to determine the correct scale and x/y coordinates of sprites that I want to contain inside of another sprite.
Let’s say I have two sprites: Game Board and Block.
Gameboard is 640x960, with a 15px border, and a pixels per unit of 100.
Block is 256x256 with a pixels per unit of 256.
I have each attached to a game object so that I can adjust them on the scene. I have the gameboard just where I want, but I’m creating 7 blocks at run time and trying to scale/fit them on the game board.
Also, the game board scale is set to .35, and both sprites pivot point is the center.
But when I calculate the coordinates/scale at run time, I get completely different values than what I see at design time.
This is the math I’m currently using.
var blockPpu = 256;
var blockPixels = 256;
var boardPpu = 100;
var boardWidth = 640;
var boardHeight = 960;
var boardGutter = 15;
var columnSize = 7;
var rowSize = 10;
var gameBoardSpriteRenderer = m_GameView.Gameboard.GetComponent<SpriteRenderer>();
var gameBoardSpriteSize = new Vector2(boardWidth - (boardGutter * 2), boardHeight - (boardGutter *2));
var gameBoardPixelsPerUnit = gameBoardSpriteRenderer.sprite.pixelsPerUnit;
var gameBoardObjectSize = new Vector2(gameBoardSpriteSize.x / gameBoardPixelsPerUnit, gameBoardSpriteSize.y / gameBoardPixelsPerUnit);
var blockObjectSize = (gameBoardObjectSize.x / columnSize) * (blockPixels / blockPpu);
var blockObjectCenterPoint = blockObjectSize / 2;
var gameBoardTopLeftX = ((gameBoardObjectSize.x / 2f) * -1) + blockObjectCenterPoint;
var gameBoardTopLeftY = (gameBoardObjectSize.y /2f) - blockObjectCenterPoint;
gameBoardTopLeftY = gameBoardTopLeftY - gameBoardSpriteRenderer.transform.localPosition.y;
var topLeftCorner = new Vector3(gameBoardTopLeftX, gameBoardTopLeftY, 10.0f);
var spriteTargetSize = blockObjectSize;
for (var y = 0; y < rowSize; y++)
{
for (var x = 0; x < columnSize; x++)
{
var location = topLeftCorner;
location.x += spriteTargetSize * x;
location.y -= spriteTargetSize * y;
var block = m_BlockFactory.Create();
block.transform.localScale = new Vector3(blockObjectSize, blockObjectSize);
block.Position = location;
}
}
It’s close, but the blocks overlap the game board on the top, left, and right, and their overall y is too high. Any ideas? I’m still pretty new to Unity, and I’m barely grasping the concept of world units. I’ve been a web developer for a long time and I’m primarily used to pixels in a precise layout.