SKPhysicsContact有什么方法可以确定A和B是哪个物体? [英] SKPhysicsContact is there any way to determine which body is A and B?

查看:53
本文介绍了SKPhysicsContact有什么方法可以确定A和B是哪个物体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SpriteKit中,我们在didBeginContact方法中检测到了.但这看起来有点愚蠢:func didBeginContact(contact:SKPhysicsContact){

in SpriteKit we detect the in the didBeginContact method. but this looks a bit stupid to do something like that: func didBeginContact(contact: SKPhysicsContact) {

    if let contactA = contact.bodyA.node?.name {

        if let contactB = contact.bodyB.node?.name {

            //now that we have safely unwrapped these nodes, we can operate on them

            if contactA == "ball" {

                collisionBetweenBall(contact.bodyA.node!, object: contact.bodyB.node!)

            } else if contactB == "ball" {

                collisionBetweenBall(contact.bodyB.node!, object: contact.bodyA.node!)

            }

        }

    }

}

有什么方法可以确保bodyA始终是球吗?有没有与categorybitmask相关的规则?

is there any way I can ensure that bodyA is always a ball? is there any rules related to categorybitmask?

推荐答案

如果您使用的是简单类别,并且每个物理主体仅属于一个类别,则didBeginContact的这种替代形式可能更易读:

If you are using simple categories, with each physics body belonging to only one category, then this alternative form of didBeginContact may be more readable:

func didBeginContact(contact: SKPhysicsContact) {
    let contactMask = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

switch contactMask {

   case categoryBitMask.ball | categoryBitMask.something:
       print("Collision between ball and something")
       let ballNode = contact.bodyA.categoryBitMask == categoryBitMask.ball ? contact.bodyA.node! : contact.bodyB.node!
       ballNode.pop()
       score += 10

   default :
       //Some other contact has occurred
       print("Some other contact")
   }
}

请注意,如果您的类别比较复杂,则将无法使用,因为简单的AND测试( categoryBitMask.ball | categoryBitMask.something )将不匹配.

Note that if your categories are more complicated, this won't work as the simple AND tests (categoryBitMask.ball | categoryBitMask.something) won't match.

这篇关于SKPhysicsContact有什么方法可以确定A和B是哪个物体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆