如何创建几乎与GameScene接壤的坐标?

时间:2015-09-29 18:30:20

标签: ios swift random sprite-kit swift2

我正在尝试生成几乎与屏幕边缘接壤的圆圈。我尝试创建自己的坐标生成器,我的问题是我随机生成的圆圈只出现在屏幕的顶部和底部。以下是它正在做的截图: http://imgur.com/oP5Wvne

我不知道为什么会这样,因为当我打印圆圈位置的x和y坐标时,它表示两个点都小于框架的宽度和高度。在我的GameScene.swift中,我称之为此功能。

    private func generateRandomCoorindates() -> CGPoint {

    let randomNumber = arc4random_uniform(2)
    var xCoordinate: Double
    var yCoordinate: Double
    if randomNumber == 0 {
        var _xCoordinate: Double {
           let _randomNumber = arc4random_uniform(2)
            //x-corrdinate either 50 or width-50
            if _randomNumber == 0 {
                return 50
            } else {
                return Double(self.frame.width - 50)
            }
        }
        xCoordinate = _xCoordinate
        //random y-coordinate from 50 to height-50
        yCoordinate = Double.random(lower: 50, upper: Double(self.frame.height) - 50)
    }
    else {
        //random x-coordinate from 50 to width-50
        xCoordinate = Double.random(lower: 50, upper: Double(self.frame.width) - 50)
        var _yCoordinate: Double {
            //y-coordinate either 50 or height - 50
            let _randomNumber = arc4random_uniform(2)
            if _randomNumber == 0 {
                return 50
            } else {
                return Double(self.frame.height - 50)
            }
        }
        yCoordinate = _yCoordinate
        }
    return CGPoint(x: CGFloat(xCoordinate), y: CGFloat(yCoordinate))
    }

我的扩展名是:

public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T {
var r: T = 0
arc4random_buf(&r, Int(sizeof(T)))
return r
}

public extension Double {
    public static func random(lower lower: Double, upper: Double) -> Double {
        let r = Double(arc4random(UInt64)) / Double(UInt64.max)
        return (r * (upper - lower)) + lower
    }
 }

1 个答案:

答案 0 :(得分:1)

我不确定为什么当你只需要一个计算属性时,你选择扩展Double - 这似乎是过于复杂的事情。这是一个在屏幕边缘某处返回随机点的函数,需要的代码少得多。

let screenwidth = UIScreen.mainScreen().bounds.width
let screenheight = UIScreen.mainScreen().bounds.height

func randomCoordinates -> CGPoint {
    var coordinates = CGPoint()

    let randomX = arc4random(screenwidth) - screenwidth/2  // subtracting half of the screen to center it
    let randomY = arc4random(screenheight) - screenheight/2

    let randomDirection = arc4random_uniform(4)
    switch randomDirection {
    case 0: returnCoordinates = CGPoint(x: randomX, y: screenheight/2)  // north edge
    case 1: returnCoordinates = CGPoint(x: screenwidth/2, y: randomY)  // east edge
    case 2: returnCoordinates = CGPoint(x: randomX, y: -screenheight/2)  // south edge
    case 3: returnCoordinates = CGPoint(x: -screenwidth/2, y: randomY)  // west edge
    }

    return coordinates
}