I am making a Breakout Game and the Game generates rows from how ever many bricks I want in that row. But I cannot get the rows to start in the center. How would I achieve this, here is my current code.
I’ve tried numerous things, but the closest I got was to get them all to be in the middle, but the should spread out from the middle.
What I would like to achieve should look something like this.
2
Answers
You’re adding the bricks into a parent
SKNode
(usingaddChild(_:)
). Everything added in that parent node is relative to its coordinate space.Try adding a brick at
y: 0
and see where will it be positioned. If your scene has theanchorPoint
at 0.5, you will likely see the brick in the center of the screen. From there, you go up or down (positive or negativey
values) to show other rows.To better understand how the coordinate system works, see About SpriteKit Coordinate Systems.
It’s the same for the x axis. If your bricks start from left to right, that means the parent node has its origin to the left of the screen.
To start from the middle, you need to know the middle point. One option is to make a container node, position that in the center of the screen, and add all the bricks there. Like that, the bricks can start at
(0, 0)
.It really depends on how you set up your node hierarchy.
If you have the maximum row size available, a simple way is to include an offset when you calculate the x coordinate.
If things might not divide evenly (e.g., if
maxRow
is 15 like it seems to be in your pictures, butrow
could be 4) then you have to decide on what behavior you’d like. The above will keep bricks aligned because the integer division in calculatingpadding
will truncate; the left and right padding won’t be the same. If you use floating division and get apadding
like 3.5, you’d get perfectly centered rows but odd rows and even rows would have different alignment.If your problem is that you want things to appear in an animated way (like in your picture), then things are more complicated. Instead of generating based on the sequence 1, 2, …,
row
, it’s probably easier to think about generating from the sequence 0, +1, -1, +2, -2, … After generating the center brick, you’d do the generation of additional bricks in pairs. The x coordinates would be calculated asxCenter + i * Int(brick.side.width)
.