我正在使用 Xcode、SpriteKit 和 Swift 构建我的第一款 iPhone 游戏。我对这些技术不熟悉,但我熟悉一般的编程概念。
这是我想用英语做的事情。我想让圆圈随机出现在屏幕上,然后开始变大。但是,我不希望在当前存在圆圈的位置出现圆圈。我无法确定每个圆圈的位置。
在 GameScene.swift 中,我在 didMoveToView 中有以下代码:
runAction(SKAction.repeatActionForever(
SKAction.sequence([
SKAction.runBlock(addCircle), SKAction.waitForDuration(3, withRange: 2)]
)))
上面的这段代码调用了我的“addCircle”方法:
func addCircle() {
// Create sprite.
let circle = SKSpriteNode(imageNamed: "grad640x640_circle")
circle.name = "circle"
circle.xScale = 0.1
circle.yScale = 0.1
// Determine where to position the circle.
let posX = random(min: 50, max: 270)
let posY = random(min: 50, max: 518)
// ***Check to see if position is currently occupied by another circle here.
circle.position = CGPoint(x: posX, y: posY)
// Add circle to the scene.
addChild(circle)
// Expand the circle.
let expand = SKAction.scaleBy(2, duration: 0.5)
circle.runAction(expand)
}
上面的随机函数只是在给定范围内选择一个随机数。我如何检查我的随机函数是否正在生成一个当前被另一个圆圈占据的位置?
我正在考虑使用 do..while 循环随机生成一组 x 和 y 坐标,然后检查该位置是否有圆圈,但我找不到如何检查该条件。任何帮助将不胜感激。
最佳答案
在这方面有几种方法可以帮助您:
(BOOL) intersectsNode:(SKNode*)node
,可用于 SKNode,并且CGRectContainsPoint()
以及CGRectContainsRect()
方法。
例如,检查交叉点的循环如下所示:
var point: CGPoint
var exit:Bool = false
while (!exit) {
let posX = random(min: 50, max: 270)
let posY = random(min: 50, max: 518)
point = CGPoint(x: posX, y: posY)
var pointFound: Bool = true
self.enumerateChildNodesWithName("circle", usingBlock: {
node, stop in
let sprite:SKSpriteNode = node as SKSpriteNode
if (CGRectContainsPoint(sprite.frame, point))
{
pointFound = false
stop.memory = true
}
})
if (pointFound)
{
exit = true
}
}
//point contains CGPoint where no other circle exists
//Declare new circle at point
关于ios - 检查场景中的位置是否被 Sprite 占用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26986625/