SKPhysicsContactDelegate,碰撞无法按我想要的方式工作

时间:2019-10-19 22:34:38

标签: swift sprite-kit

我想知道如何使联系人代表正常工作。我确实有联系,但我希望每块被球击中的砖块都消失。

我已经用它撞砖墙了太久了。一个接一个的教程似乎并没有带我到任何地方。我可能需要采取一些步骤,但不确定如何开始。

我已经尝试了很多关于YouTube的教程,以及我在网上可以找到的任何教程。

enum CollisionType: UInt32 {

   case ball = 1
   case paddle = 2
   case walls = 4
   case brick = 8

}

class Brick: SKSpriteNode  { }


class GameScene: SKScene, SKPhysicsContactDelegate {

   let bricks = ["brickPurple","brickGreen", "brickRed"]
   let brick = SKSpriteNode(imageNamed: "brickPurple")

   let ball = SKSpriteNode(imageNamed: "ball")
   let paddle = SKSpriteNode(imageNamed: "paddle")



    override func didMove(to view: SKView) {

      physicsWorld.contactDelegate = self


      physicsBody = SKPhysicsBody(edgeLoopFrom: frame.inset(by: UIEdgeInsets(top: 0, left: 0 , bottom: 0 , right: 0 )))


      ball.name = "ball"
      ball.size = CGSize(width: 20, height: 20)
      ball.position.x = frame.maxX/2
      ball.position.y = 70
     addChild(ball)


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

      ball.physicsBody?.restitution = 1
      ball.physicsBody?.linearDamping = 0
      ball.physicsBody?.friction = 0
      ball.physicsBody?.applyImpulse(CGVector(dx: 0, dy: 20))
      ball.physicsBody?.contactTestBitMask = ball.physicsBody!.collisionBitMask


      paddle.name = "paddle"
      paddle.size = CGSize(width: 100, height: 20)
      paddle.position.x = frame.maxX/2
      paddle.position.y = 50
      paddle.physicsBody = SKPhysicsBody(rectangleOf: paddle.size)
      paddle.physicsBody?.isDynamic = false



      let brickWidth = brick.frame.width
      let brickHeight = brick.frame.height

      for i in stride(from: view.bounds.minX + brickWidth, to: view.bounds.maxX - brickWidth, by: brickWidth ) {

         for j in stride(from: view.bounds.minX  + brickHeight + 375, to: view.bounds.maxX + 200, by: brick.frame.height + 0) {

            let brickType = bricks.randomElement()!

            let brick = Brick(imageNamed: brickType)

            brick.position = CGPoint(x: i, y: j)

            brick.physicsBody = SKPhysicsBody (rectangleOf: brick.size)


            brick.physicsBody?.isDynamic = false

            brick.name = "brick"

            addChild(brick)


         }


         }

      }}

我以前有func didBegin(_ contact: SKPhysicsContact)的一些代码,但是我刚刚决定重新开始。

1 个答案:

答案 0 :(得分:0)

这不是您问题的具体答案,但是,如果您按照以下答案(尤其是第一个答案)中的步骤进行操作,我想您的代码将起作用:

我的碰撞和接触逐步指南: https://stackoverflow.com/a/51041474/1430420

以及碰撞和接触的指南测试位掩码: https://stackoverflow.com/a/40596890/1430420

操纵位掩码可打开和关闭单个碰撞和触点。 https://stackoverflow.com/a/46495864/1430420