我正在尝试生成几乎与屏幕边缘接壤的圆圈。我尝试创建自己的坐标生成器,我的问题是我随机生成的圆圈只出现在屏幕的顶部和底部。这是它正在做的事情的截图: 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
}
}
最佳答案
当您只需要一个计算属性时,我不确定您为什么选择扩展 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
}
关于ios - 如何创建几乎与我的 GameScene 接壤的坐标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32851306/