Swift:sprite碰撞检测没有制作物理体?

时间:2015-04-07 02:03:35

标签: swift sprite-kit collision-detection

好吧,所以我对sprite kit很新,我在Swift工作。我有2个精灵节点,saviorchicken1savior有一个物理机构,这就是我设置它的方式:

var saviorTexture = SKTexture(imageNamed: "1.png")
saviorTexture.filteringMode = SKTextureFilteringMode.Nearest

savior = SKSpriteNode(texture: saviorTexture)
savior.setScale(0.2)
savior.position = CGPoint(x: self.frame.size.width * 0.5, y: self.frame.size.height * 0.2)
savior.physicsBody?.dynamic = true
savior.physicsBody?.allowsRotation = false
savior.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(savior.size.width, savior.size.height))

        self.addChild(savior)

chicken1现在没有物理机构:

var chickenTexture = SKTexture(imageNamed: "block1")

        chicken1 = SKSpriteNode(texture: chickenTexture)
        chicken1.setScale(0.75)
        chicken1.position = CGPoint(x: self.size.width * 0.38, y: self.size.height * 1.2)
        self.addChild(chicken1)

我需要知道如何在这些物体之间进行碰撞检测(即,如果救世主和鸡1接触,执行此操作),最好不要使chicken1成为物理体。

当我使chicken1成为一个物理身体时,突然变得不稳定并移动其他物体。

如果在没有物理的情况下没有办法进行碰撞检测,我怎样才能使chicken1成为一个不受任何影响的物理体,直接穿过其他物理体?

EDIT **************

所以我跟着beginner swift sprite kit - node collision detection help (SKPhysicsContact)并且:

  1. 将我的课程改为SKPhysicsContactDelegate

    类GameScene:SKScene,SKPhysicsContactDelegate {

  2. 写下以下内容:

        self.physicsWorld.contactDelegate = self
    
        savior.physicsBody?.categoryBitMask = saviorCategory
        savior.physicsBody?.contactTestBitMask = animalCategory
        savior.physicsBody?.collisionBitMask = 0
    
        chicken1.physicsBody?.categoryBitMask = animalCategory
        chicken1.physicsBody?.contactTestBitMask = saviorCategory
        chicken1.physicsBody?.collisionBitMask = 0
    
        func didBeginContact(contact: SKPhysicsContact) {
    
        var saviorPhysics: SKPhysicsBody
        var chicken1Physics: SKPhysicsBody
    
        if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask
        {
            saviorPhysics = contact.bodyA
            chicken1Physics = contact.bodyB
        }
        else {
            saviorPhysics = contact.bodyB
            chicken1Physics = contact.bodyA
        }
    
        if saviorPhysics.categoryBitMask == 0 && chicken1Physics.categoryBitMask == 1 {
            self.chicken1.removeFromParent()
        }
    
    }
    
  3. 我跑了它并且没有错误,但它不起作用。

1 个答案:

答案 0 :(得分:2)

您可以使用categoryBitMask执行此操作,并通过回复SKSceneContactDelegate来自行处理冲突。

通过这种方式,您可以为不同的节点设置不同的类别,并根据需要处理不同类别之间的冲突。

<强>教程:

http://seodoa.com/2014/04/01/skphysicsbody-react-to-contact-but-not-to-collide/