Swift SpriteKit 获取可见帧大小

标签 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

最佳答案

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

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

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

关于Swift SpriteKit 获取可见帧大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29221424/

相关文章:

swift - 合并/追加 [AnyHashable : Any]() on Swift 3

ios - 使用 addSubView 将 View 添加到另一个 View 后调整 View 大小

java - 关闭单个窗口会关闭java中的所有框架

ios - UIButton 的错误坐标

algorithm - 在证明Big O、Big Omega和Big Theta时,我们如何识别C和n0?

objective-c - self.view.bounds.size.width 返回错误值

ios - 每当我的应用程序打开时,您如何检查日期是否已更改? swift

swift - 在展开可选值 prepareForSegue 时意外发现 nil

ios - 整数错误

Swift Frames 全部不对齐