Swift SpriteKit获得可见的帧大小

ork*_*675 1 frame bounds skview swift

我一直在尝试使用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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

球落下的框架

ork*_*675 10

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

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

谢谢@ABakerSmith指出我正确的方向.


ABa*_*ith 5

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

if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
    scene.size = skView.frame.size
    skView.presentScene(scene)
}
Run Code Online (Sandbox Code Playgroud)

或在didMoveToView您的SKScene子类中:

override func didMoveToView(view: SKView) {
     super.didMoveToView(view)
     self.size = view.frame.size
}
Run Code Online (Sandbox Code Playgroud)