【问题标题】:Gravity property not working in SpriteKit Scene重力属性在 SpriteKit 场景中不起作用
【发布时间】:2015-11-10 21:21:41
【问题描述】:
import SpriteKit

class GameScene: SKScene {
 override func didMoveToView(view: SKView) {
    /* Setup your scene here */
 }

 override func touchesBegan(touches: Set<UITouch>, withEvent event:            UIEvent?) {
   /* Called when a touch begins */

    for touch in touches {
        let location = touch.locationInNode(self)

        let sprite = SKSpriteNode(imageNamed:"Beach Ball-100")
        self.addChild(sprite)

        sprite.xScale = 0.5
        sprite.yScale = 0.5
        sprite.position = location
        sprite.color = UIColor.redColor()
        sprite.physicsBody = SKPhysicsBody(edgeLoopFromRect:self.frame)
        sprite.physicsBody?.affectedByGravity = true
        var action = SKAction.rotateByAngle(CGFloat(M_PI), duration:1)

  }
  }

  }

上面的代码出现在我的场景类中。当我运行它时,由于重力属性设置为 true,球对象没有像预期的那样下降。请解释我做错了什么。

【问题讨论】:

    标签: ios swift sprite-kit skphysicsbody


    【解决方案1】:

    Physicsbody 是错误的。你需要的是精灵的框架,而不是世界的框架:

    sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.frame.size)
    

    【讨论】:

    • 斯特凡,感谢您的回复。我使用了 circleOfRadius,它开始工作了。
    • 顺便说一句,如果我想添加碰撞检测,即我希望球在到达屏幕底部后反弹。我怎么做?谢谢。
    • 很高兴听到。快乐编码
    • 您必须添加额外的精灵和碰撞位掩码。这是一个很好的教程:raywenderlich.com/84341/create-breakout-game-sprite-kit-swift
    • 谢谢 Stefan .. 这很有帮助。那么,每次我们需要在屏幕边缘设置边框时,我可以使用以下代码吗? let borderBody = SKPhysicsBody(edgeLoopF​​romRect: self.frame) // 2. 设置那个physicsBody 的摩擦力为0 borderBody.friction = 0 // 3. 设置场景的physicsBody 为borderBody self.physicsBody = borderBody
    【解决方案2】:

    添加SKPhysicsContactDelegate:

    class GameScene: SKScene, SKPhysicsContactDelegate 
    

    didMoveToViewtouchesBegan 中定义您的physicsWorld(就像您在示例中所做的那样)

    physicsWorld.gravity = CGVectorMake(0, -1.0)
    physicsWorld.contactDelegate = self
    

    给你的节点适当的SKPhysicsBody 大小

    sprite.physicsBody = SKPhysicsBody(circleOfRadius: frame.size.width / 2)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-03
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多