Swift SpriteKit获得可见的帧大小 [英] Swift SpriteKit get visible frame size

查看:66
本文介绍了Swift SpriteKit获得可见的帧大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been trying to create a simple SpriteKit app using Swift. The purpose is to have a red ball re-locate itself on the screen when clicked on. But the variables self.frame.width and self.frame.height do not return the boundaries of the visible screen. Instead they return boundaries of the whole screen. Because I am choosing the location of the ball at random I need the visible boundaries. Couldn't find an answer after hours of research. How can I achieve this?

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()
        }
    }
}

推荐答案

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

Adding this bit of code to the GameViewController seems to have fixed the issue.

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

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

Thank you @ABakerSmith for pointing me in the right direction.

这篇关于Swift SpriteKit获得可见的帧大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆