ios - 检查场景中的位置是否被 Sprite 占用

标签 ios swift sprite-kit

我正在使用 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 坐标,然后检查该位置是否有圆圈,但我找不到如何检查该条件。任何帮助将不胜感激。

最佳答案

在这方面有几种方法可以帮助您:

  1. (BOOL) intersectsNode:(SKNode*)node,可用于 SKNode,并且
  2. 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/

相关文章:

ios - 更新后,iOS应用程序从通知中心消失

ios - 自动增加/减少 UITableViewCell 中的 UILabelView 高度?

ios - iPad 模拟器上的 SKScene 问题无法填满 Xcode 11 beta 7 中的屏幕

ios - 如何为倒计时器创建循环进度指示器

Swift 3 Physicsbody 碰撞不起作用

ios - 如果我想给自己分配一个属性怎么办?

iphone - IOS CATransform3DMakeRotation 需要矢量方面的帮助

ios - 在 Swift 3+ 中生成假触摸

ios - 在 Swift 3 中单独按下按钮时制作标签文本 "blink"或 "flash"

ios - SQLite 编码问题