更改 SKSpriteNode 的 x 位置
Changing x position of SKSpriteNode
我正在 运行 在我的游戏中使用 for 循环来生成 SKSpriteNodes。
我希望我的第一个块从 (20, 40) 开始,每个新块的 x 位置加 20,y 位置加 40。
第一块 (20, 40)
第二块 (40, 80)
第三座 (60, 120)
等等。
y 位置按照我想要的方式运行,但是 x 位置会随机从我屏幕上的任何位置开始,然后为每个生成的新块添加 20。
下面是我的代码。
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)
}
}
我还添加了打印语句,说明当我 运行 代码时它的样子。
下面是块的x和y位置的打印语句。
我试过调换 xP 和 yP 初始化的顺序。那没有用。
有什么建议吗?
我更愿意将 while loops 用于这种您必须从一开始就施加条件的操作,例如限制:
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)
}
}
输出:
我正在 运行 在我的游戏中使用 for 循环来生成 SKSpriteNodes。
我希望我的第一个块从 (20, 40) 开始,每个新块的 x 位置加 20,y 位置加 40。
第一块 (20, 40) 第二块 (40, 80) 第三座 (60, 120) 等等。
y 位置按照我想要的方式运行,但是 x 位置会随机从我屏幕上的任何位置开始,然后为每个生成的新块添加 20。
下面是我的代码。
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)
}
}
我还添加了打印语句,说明当我 运行 代码时它的样子。
下面是块的x和y位置的打印语句。
我试过调换 xP 和 yP 初始化的顺序。那没有用。
有什么建议吗?
我更愿意将 while loops 用于这种您必须从一开始就施加条件的操作,例如限制:
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)
}
}
输出: