提前致谢。 我使用
在屏幕中间设置了一个圆圈circle = SKShapeNode(circleOfRadius: 100 ) // Size of Circle
circle.position = CGPointMake(frame.midX, frame.midY) //Middle of Screen
circle.strokeColor = SKColor.whiteColor()
circle.glowWidth = 1.0
circle.fillColor = SKColor.orangeColor()
self.addChild(circle)
我尝试做的是,当用户点击屏幕时,精灵将从随机位置出现,并向屏幕中心移动。我得到的问题是,有时精灵会出现在圆圈内。所以我的计划是让精灵从屏幕外侧向中心移动。我怎样才能做到这一点?
以下是我对随机位置
所做的代码let randomX = CGFloat(arc4random()) % self.frame.weith
let randomY = CGFloat(arc4random()) % self.frame.height
然后设置精灵
sprite.position = CGPointMake(randomX, randomY)
我尝试了以下设置sprite的随机位置,它们都没有工作
let randomX = Int(arc4random_uniform(UInt32(self.frame.width + self.frame.width / 2))) || Int(arc4random_uniform(UInt32(self.frame.width - self.frame.width / 2)))
let randomY = Int(arc4random_uniform(UInt32(self.frame.height + self.frame.height / 2))) || Int(arc4random_uniform(UInt32(self.frame.height - self.frame.height / 2)))
和
let randomX = (CGFloat(arc4random()) % self.frame.width + self.frame.width / 2) || (CGFloat(arc4random()) % self.frame.width - self.frame.width / 2)
let randomY = (CGFloat(arc4random()) % self.frame.height + self.frame.height / 2) || (CGFloat(arc4random()) % self.frame.height - self.frame.height / 2)
答案 0 :(得分:1)
要在Swift中生成随机位置,您可以使用以下内容:
var randomX = CGFloat(Int(arc4random()) % width)
var randomY = CGFloat(Int(arc4random()) % height)
现在要在屏幕外生成一个随机位置,您需要在4个可能的位置生成位置 - 屏幕左侧,右侧,顶部或底部。
基本上,这是你试图用你的||做的但是,这不适用于分配非布尔变量。
示例:
func randomPointOffscreen() -> CGPoint
{
let spawn = arc4random_uniform(4)+1
var randomX:CGFloat = -100
var randomY:CGFloat = 100
switch(spawn)
{
case 1:
randomX = -CGFloat(Int(arc4random()) % 320)
randomY = CGFloat(Int(arc4random()) % 640)
break;
case 2:
randomX = 320 + CGFloat(Int(arc4random()) % 320)
randomY = CGFloat(Int(arc4random()) % 640)
break;
case 3:
randomX = CGFloat(Int(arc4random()) % 320)
randomY = 640 + CGFloat(Int(arc4random()) % 640)
break;
case 4:
randomX = CGFloat(Int(arc4random()) % 320)
randomY = -CGFloat(Int(arc4random()) % 640)
break;
default:
break;
}
return CGPointMake(randomX, randomY)
}