找不到会员applyimpulse

时间:2015-01-20 08:44:43

标签: ios macos xcode6.1 swift-playground

无法应用冲动,在xcode6.1 osx playground中收到错误“找不到成员applyimpulse”。

代码:

func spawnSand() {

    let sand: SKSpriteNode = SKSpriteNode(imageNamed: "sand")
    sand.position = CGPoint(x: random(min:0 , max: scene.size.width), 
    y: scene.size.height - sand.size.height)

    sand.physicsBody = SKPhysicsBody(circleOfRadius: sand.size.width/2)
    sand.physicsBody!.restitution = 0.9
    sand.physicsBody!.density = 20.0
sand.name = "sand"
scene.addChild(sand)
}

func shake() {

    scene.enumerateChildNodesWithName("sand") { node, _ in
    node.physicsBody.applyImpulse(
      CGVector(dx:0 , dy: random(min: 20 ,max:40))
    )
    }
   }

3 个答案:

答案 0 :(得分:0)

node.physicsBody返回一个可选项。在使用之前打开它

e.g。

if let SKPhysicsBody body = node.physicsBody {  
    body.applyImpulse( ... )
}

答案 1 :(得分:0)

请尝试使用以下代码,并告诉我它是否正常工作..

func spawnSand(){

let sand: SKSpriteNode = SKSpriteNode(imageNamed: "sand")
sand.position = CGPoint(x: random(min:0 , max: scene.size.width), 
y: scene.size.height - sand.size.height)
sand.physicsBody = SKPhysicsBody(circleOfRadius: sand.size.width/2)
sand.physicsBody!.restitution = 0.9
sand.physicsBody!.density = 20.0
sand.name = "sand"
scene.addChild(sand)}

func shake(){

 scene.enumerateChildNodesWithName("sand") { node, _ in 
 let impulse = CGVector(dx:random(min: 20 , max:60) ,dy:
 random(min: 20 , max:60))
 node.physicsBody?.applyImpulse( impulse) 
 }
}

答案 2 :(得分:0)

不幸的是,我遇到了一个奇怪的问题,其中.applyImpulse不会接受传递给它的CGVector构造函数。我不得不将CGVector变量分开,然后一切正常。另外,physicsBody是一个可选项,必须在使用前解包:

func shake() {
    scene.enumerateChildNodesWithName("sand") { node, _ in
        let impulse = CGVector(dx: 0, dy: random(min: 20, max: 40))
        node.physicsBody?.applyImpulse(impulse)
    }

    scene.enumerateChildNodesWithName("shape") {
        node, _ in
        let impulse = CGVector(dx: random(min: 20, max: 60), dy: random(min: 20, max: 60))
        node.physicsBody?.applyImpulse(impulse)
    }
}