Swift 4中两个节点之间的冲突检测

时间:2018-07-13 13:08:11

标签: swift sprite-kit collision-detection

我想在化身与障碍物之间进行碰撞检测,因此,每当发生碰撞时,它都应打印“碰撞”,但即使这样也不起作用,所以问题是,它无法检测到任何碰撞。而且,如果发生碰撞,应该区分玩家和障碍物。

#Determine if we have an overlap between an input and an output
for item in canvas.find_all():
    tags = canvas.gettags(item)
    if tag in tags:
        if 'input' in tags:
            #current item is an input of the moved object
            #Get the items coordinates
            coords = canvas.coords(item)
            #Find if we overlap with other objects
            closest = canvas.find_overlapping(coords[0]-5,coords[1]-5,coords[2]+5,coords[3]+5)
            for closest_item in closest:
                closest_tags = canvas.gettags(closest_item)
                if 'output' in closest_tags:
                    #If we overlap with another object, print connected and the appropriate tags
                    print("connected", closest_tags, "-", tag)
                    connected_coords = canvas.coords(closest_item)
                    snapx = coords[0] - connected_coords[0]
                    snapy = coords[1] - connected_coords[1]
                    canvas.move(tag, -snapx, -snapy)

1 个答案:

答案 0 :(得分:0)

首先,avatarCategory和障碍物类别都为0,因为:UInt32 = 0 * 1 << 1 = 0,所以我们要解决此问题:

let avatarCategory: UInt32 = 1 << 0
let obstacleCategory: UInt32 = 1 << 1

现在contactTestBitMask表示您希望收到有关其联系人的通知的对象,因此您需要更改它:

avatar.physicsBody?.contactTestBitMask = obstacleCategory

obstacle.physicsBody?.contactTestBitMask = avatarCategor

暂时尝试

编辑:我关于碰撞和接触的循序渐进指南: https://stackoverflow.com/a/51041474/1430420

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