I am running a for loop in my game that would generate SKSpriteNodes.
I want my first block to start at (20, 40) and add 20 to the x position and 40 to the y position for every new block.
First block (20, 40) Second block (40, 80) Third Block (60, 120) And so on.
The y position is behaving the way I want to, however the x position would randomly start anywhere on my screen then add 20 for every new block generated.
Below is my code.
func generateBlocks() {
for _ in 1..<5 {
xP += 20
yP += 40
let xx = CGFloat (xP)
let yy = CGFloat (yP)
print("x position: \(xx)")
print("y position: \(yy)")
let resourcePath = NSBundle.mainBundle().pathForResource("Blocks", ofType: "sks")
let blocks = MSReferenceNode(URL: NSURL (fileURLWithPath: resourcePath!))
blocks.goals.position = CGPoint (x: xx,y: yy)
addChild(blocks)
}
}
I also added the print statement of how it would look like when I run the code.
Below is the print statement of the x and y positions of the blocks.
I tried switching the order of the xP and yP initializing. That didn't work.
Any suggestions?
I would prefer to use while loops for this kind of operations where you must impose a condition from start, for example limits:
class GameScene: SKScene {
let deltaX:CGFloat = 20.0
let deltaY:CGFloat = 40.0
override func didMoveToView(view: SKView) {
let widthLimit = self.frame.width-40
let heightLimit = self.frame.height-140
let startX:CGFloat = 80.0
drawStair(startX,limits:CGSizeMake(widthLimit,heightLimit))
}
func drawStair(startFromX:CGFloat,limits:CGSize) {
var currentX:CGFloat = startFromX
var currentY:CGFloat = startFromX+deltaY
while currentX<limits.width && currentY<limits.height {
drawBlock(CGPointMake(currentX,currentY))
currentX += deltaX
currentY += deltaY
}
}
func drawBlock(position: CGPoint,size:CGSize = CGSizeMake(40,40)) {
let block = SKSpriteNode(color: UIColor.redColor(), size: size)
block.position = position
block.name = "block"
addChild(block)
}
}
Output:
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments