2

我一直在尝试使用 Swift 创建一个简单的 SpriteKit 应用程序。目的是让一个红球在点击时重新定位在屏幕上。但是变量 self.frame.width 和 self.frame.height 不返回可见屏幕的边界。相反,它们返回整个屏幕的边界。因为我随机选择球的位置,所以我需要可见的边界。经过数小时的研究后找不到答案。我怎样才能做到这一点?

var dot = SKSpriteNode()
let dotScreenHeightPercantage = 10.0
let frameMarginSize = 30.0

override func didMoveToView(view: SKView) {

    var dotTexture = SKTexture(imageNamed: "img/RedDot.png")
    dot = SKSpriteNode(texture: dotTexture)
    dot.size.height = CGFloat( Double(self.frame.height) / dotScreenHeightPercantage )
    dot.size.width = dot.size.height
    dot.name = "dot"

    reCreateDot()
}

func reCreateDot() {
    dot.removeFromParent()

    let dotRadius = Double(dot.size.height / 2)
    let minX = Int(frameMarginSize + dotRadius)
    let maxX = Int(Double(self.frame.width) - frameMarginSize - dotRadius)
    let minY = Int(frameMarginSize + dotRadius)
    let maxY = Int(Double(self.frame.height) - frameMarginSize - dotRadius)
    let corX = randomInt(minX, max: maxX)
    let corY = randomInt(minY, max: maxY)
    println("result: \(corX) \(corY)")
    dot.position = CGPoint(x: corX, y: corY)

    self.addChild(dot)
}

func randomInt(min: Int, max:Int) -> Int {
    return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        let node = nodeAtPoint(location)
        if node.name == "dot" {
            println("Dot tapped.")
            reCreateDot()
        }
    }
}

框架落球

4

2 回答 2

11

将这段代码添加到 GameViewController 似乎已经解决了这个问题。

            /* Set the scale mode to scale to fit the window */
            scene.scaleMode = .AspectFill
            scene.size = skView.bounds.size
            skView.presentScene(scene)

感谢@ABakerSmith 为我指明了正确的方向。

于 2015-03-29T13:52:16.757 回答
5

我尝试使用您的代码并设置场景的大小解决了这个问题。如果您要取消归档场景,其大小将是 sks 文件中设置的大小。因此,您需要将场景的大小设置为您的 SKView 的大小。

if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
    scene.size = skView.frame.size
    skView.presentScene(scene)
}

或在didMoveToView您的SKScene子类中:

override func didMoveToView(view: SKView) {
     super.didMoveToView(view)
     self.size = view.frame.size
}
于 2015-03-26T11:35:18.393 回答