Reputation: 587
I am trying to generate circles that nearly border the edge of the screen. I tried creating my own coordinate generator, my issue is that the circles that I am randomly generating are only appearing at the top and bottom of the screen. Here is a screenshot of what it is doing: https://i.sstatic.net/WBUSP.jpg
I have no idea why this is happening because when I print the x and y coordinate of the circle's position, it says that both points are less than the frame's width and height. In my GameScene.swift
I call this function.
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))
}
My extensions are:
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
}
}
Upvotes: 0
Views: 70
Reputation: 1086
I'm not certain why you've chosen to extend Double
when you only need one computed property - it seems to be overcomplicating things. Here's a function that will return a random point somewhere along the edge of the screen, and requires a lot less code.
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
}
Upvotes: 1