Sprite Kit 超过 1 次碰撞

Sprite Kit more than 1 time collision

我的游戏不是这样的,而是这样的:

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {
    var sprite = SKSpriteNode()

    override func didMoveToView(view: SKView)
    {
        self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
        self.physicsBody?.categoryBitMask = 1
        self.physicsBody?.contactTestBitMask = 1
        self.physicsWorld.gravity = CGVectorMake(0, -10)
        self.physicsWorld.contactDelegate = self



    }
    func didBeginContact(contact: SKPhysicsContact) {
        print("contact")
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
    {
        let spriteTexture = SKTexture(imageNamed: "Spaceship")
        sprite = SKSpriteNode(texture: spriteTexture)
        sprite.position = CGPoint(x: CGRectGetMidX(self.frame) , y: CGRectGetMidY(self.frame))
        sprite.size = CGSizeMake(80, 80)
        sprite.physicsBody = SKPhysicsBody(texture: spriteTexture, size: CGSizeMake(80, 80))
        sprite.physicsBody?.categoryBitMask = 1
        sprite.physicsBody?.collisionBitMask = 1
        sprite.physicsBody?.contactTestBitMask = 1
        sprite.physicsBody?.linearDamping = 0;

        self.addChild(sprite)

    }
}

如果您粘贴此代码并且 运行 您会看到很多 "contact" 字符串。我只想要 1 个联系人: 所以我想当只接触 1 次碰撞时

我编辑了我的问题有人能帮忙吗?

1.Create 来自 Xcode 模板的“基础游戏”基于 SpriteKit
2.Paste 下面的代码到 GameScene class

class GameScene: SKScene, SKPhysicsContactDelegate {
    var sprite = SKSpriteNode()

    override func didMoveToView(view: SKView)
    {
        self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
        self.physicsBody?.categoryBitMask = 1
        self.physicsBody?.collisionBitMask = 1

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

        self.physicsBody?.restitution = 0.0

    }

    func didEndContact(contact: SKPhysicsContact) {
        print("End contact")
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?)
    {
        let spriteTexture = SKTexture(imageNamed: "Spaceship")
        sprite = SKSpriteNode(texture: spriteTexture)
        sprite.physicsBody = SKPhysicsBody(texture: spriteTexture, size: CGSizeMake(80, 80))

        sprite.size = CGSizeMake(80, 80)

        sprite.position = CGPoint(x: CGRectGetMidX(self.frame) , y: CGRectGetMidY(self.frame))
        sprite.physicsBody?.categoryBitMask = 1
        sprite.physicsBody?.collisionBitMask = 1
        sprite.physicsBody?.contactTestBitMask = 1
        sprite.physicsBody?.fieldBitMask = 1
        sprite.physicsBody?.restitution = 0

        self.addChild(sprite)

    }
}

重要提示 尝试使用 didEndContact 委托方法而不是 didBeginContact。在这种情况下,您只会获得一次调用,而 didBeginContact 会调用多次。