【问题标题】:couldn't find member applyimpulse找不到会员申请冲动
【发布时间】:2015-01-20 08:44:43
【问题描述】:

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

代码:

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))
    )
    }
   }

【问题讨论】:

    标签: ios macos xcode6.1 swift-playground


    【解决方案1】:

    node.physicsBody 返回一个可选值。使用前拆开包装

    例如

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

    【讨论】:

      【解决方案2】:

      请尝试以下代码并告诉我它是否有效..

      函数 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 摇动() {

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

      【讨论】:

        【解决方案3】:

        不幸的是,我遇到了一个奇怪的问题,即 .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)
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-13
          • 1970-01-01
          • 1970-01-01
          • 2022-08-13
          • 1970-01-01
          • 2014-06-26
          相关资源
          最近更新 更多