Spritekit Swift终止错误

时间:2015-03-04 22:46:42

标签: ios swift sprite-kit runtime-error

我正在尝试使用随机彩色背景制作精灵套件中的新应用程序,我所做的就是设置背景的颜色并在游戏中创建一个球,但它不会首先启动我&# 39;给我的代码然后错误。到目前为止,这是我的代码。

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate{

struct PhysicsCategory {
static let None      :UInt32 = 0
static let All       :UInt32 = UInt32.max
static let Triangle  :UInt32 = 0b1   //body1
static let Circle    : UInt32 = 0b10      // 2
 }

var screenWidth: CGFloat! = 0

var screenHeight: CGFloat! = 0


var circle: SKShapeNode! = SKShapeNode()
var bgColor:SKColor!
var arrayOfColors: NSMutableArray! = NSMutableArray()
var backgroundNode: SKSpriteNode! = SKSpriteNode()

override func didMoveToView(view: SKView) {
    super.didMoveToView(view)
    // Create the ball
    if screenWidth == 1024{
        circle = SKShapeNode(circleOfRadius: 22)
    }else if screenWidth == 568 || screenWidth == 480{
        circle = SKShapeNode(circleOfRadius: 11)
    }else{
        circle = SKShapeNode(circleOfRadius: 15)
    }

    circle.fillColor = SKColor.whiteColor()
    circle.alpha = 0
    circle.physicsBody = SKPhysicsBody(circleOfRadius: circle.frame.size.width/2)
    circle.physicsBody?.dynamic = true
    circle.physicsBody?.collisionBitMask = PhysicsCategory.None
    circle.physicsBody?.usesPreciseCollisionDetection = true
    circle.position = CGPoint (x: 29.952, y: 346.555)

    self.addChild(circle)

    //pick random color
    let UInt32Count = UInt32(arrayOfColors.count)
    let randomColor = arc4random_uniform(UInt32Count)
    let color: SKColor = arrayOfColors[Int(randomColor)] as SKColor

    //set random color
    let colorAction = SKAction.colorizeWithColor(color, colorBlendFactor: 1.0, duration: 1.0)
    backgroundNode.runAction(colorAction)
    backgroundNode.size = CGSize(width: 990, height: 640)

    }


 }

到目前为止,这是完整的代码,这是错误。

由于未捕获的异常终止应用程序' NSRangeException',原因:' * - [__ NSArrayM objectAtIndex:]:索引0超出空数组的范围' * 第一次抛出调用堆栈: (0x24c8d5f7 0x324ffc77 0x24ba1157 0x341ec 0x346d8 0x27fb9861 0x27fd4023 0x37888 0x379b0 0x28131c8d 0x281319fd 0x281378c7 0x2813531f 0x2819f5c1 0x283915f1 0x28393a49 0x2839e2f9 0x283922eb 0x2b4030c9 0x24c53ffd 0x24c532c1 0x24c51e1b 0x24b9eb31 0x24b9e943 0x28196127 0x28190f21 0x3a2e8 0x3a324 0x32a9baaf) libc ++ abi.dylib:以NSException类型的未捕获异常终止 (lldb)

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:3)

您已声明并初始化空数组:

var arrayOfColors: NSMutableArray! = NSMutableArray()

然后你正在尝试访问空数组:

let color: SKColor = arrayOfColors[Int(randomColor)] as SKColor

这将抛出您在控制台中显示的异常:

  

' * - [__ NSArrayM objectAtIndex:]:索引0超出范围为空   阵列'

首先需要在访问之前填充此数组,并确保在生成随机数时,它不会超出数组范围。