Sprite Kit超过1次碰撞

时间:2015-09-25 11:22:37

标签: ios swift sprite-kit sprite 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)

    }
}

如果您粘贴此代码并运行,您会看到很多“联系”字符串。我只想要1个联系方式: enter image description here 所以我想要只接触一次碰撞

我编辑了我的问题,任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

1.基于SpriteKit从Xcode模板创建'Base Game' 2.将下面的代码添加到GameScene

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多次调用时,您将只获得一次调用。