我编码如下:
func spriteCollection(count : Int) -> [SKSpriteNode]{
var spriteArray = [SKSpriteNode]()
for _ in 0..<count {
let sprite = SKSpriteNode(imageNamed: "node.png")
//giving random position to sprites, but problem is some sprites are going invisible. How do I make it appear inside the view?
let x = CGFloat(arc4random_uniform(UInt32(UIScreen.mainScreen().bounds.size.height)))
let y = CGFloat(arc4random_uniform(UInt32(UIScreen.mainScreen().bounds.size.width)))
sprite.position = CGPoint(x: x, y: y)
spriteArray.append(sprite)
}
return spriteArray
}
override func didMoveToView(view: SKView) {
let spriteCollection = spriteCollection(10)
for sprite in spriteCollection{
//facing problem here, not sure how to move it inside the view
let x = CGFloat(arc4random_uniform(UInt32(size.height)))
let y = CGFloat(arc4random_uniform(UInt32(size.width)))
let action = SKAction.moveTo(CGPoint(x: x , y: y), duration: 5)
sprite.runAction(action)
addChild(sprite)
}
}
我现在面临的问题是,如果我将计数10传递给spriteCollection
,我只能看到5或6个精灵,其余全部被隐藏。我只想让所有精灵出现在屏幕尺寸内,当我执行移动动作时,它的位置也应该在屏幕内。我在横向模式下工作。谁能帮我解决这个问题..
答案 0 :(得分:0)
您遇到的问题是屏幕的边界在处于纵向模式时面向设备,而视图的边界基于屏幕尺寸处于横向模式时。
解决问题的一种方法是在“屏幕空间”工作时撤消x和y计算
// Note how width and height appear to be "backward" here. That's because the screen
// coordinates are defined by the portrait orientation of the device,
// but the view will eventually be in a landscape orientation
let x = CGFloat(arc4random_uniform(UInt32(UIScreen.mainScreen().bounds.size.width)))
let y = CGFloat(arc4random_uniform(UInt32(UIScreen.mainScreen().bounds.size.height)))
但我认为更好的想法是等待将精灵移动到初始位置,直到创建视图,然后根据视图的边界随机定位它们而不是屏幕的界限