Swift SpriteKit获得可见的帧大小

时间:2015-03-23 22:12:07

标签: swift frame bounds skview

我一直在尝试使用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()
        }
    }
}

ball falling of frame

2 个答案:

答案 0 :(得分:10)

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

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

感谢@ABakerSmith指出我正确的方向。

答案 1 :(得分:4)

我尝试使用您的代码并设置场景的大小来解决问题。如果您要取消归档场景,则其大小将是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
}