SpriteKit touchesBegan和didBeginContact

时间:2017-05-24 12:22:37

标签: ios sprite-kit

我知道如何检测联系人中的两个对象,我知道如何检测触摸屏幕的时间。但是如果我想知道触摸屏中的两个物体是否触摸了屏幕怎么办? touchesBegan上的布尔标志如果触摸发生在联系之前,但不会在触摸期间发挥作用。

var screenTouch = false

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for _ in touches {
            screenTouch = true
        }
    }

func didBegin(_ contact: SKPhysicsContact) {

    let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    switch collision {
    case PhysicsCategories.Ball | PhysicsCategories.Edge:

        if screenTouch {
            print("LAUNCH!")
        }
etc.

1 个答案:

答案 0 :(得分:1)

您必须创建一个条件变量,该变量在didBegin时为true,在didEnd时为false。在你的touchesBegin完成你的行动,而条件变量是真的。

var yourBodiesInContact = false

func didBegin(_ contact: SKPhysicsContact) {

    let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    if collision == PhysicsCategory.Ball | PhysicsCategory.Edge {
        yourBodiesInContact = true
    }
}

func didEnd(_ contact: SKPhysicsContact) {
    let collision = contact.bodyA.categoryBitMask | contact.bodyB.categoryBitMask

    if collision == PhysicsCategory.Ball | PhysicsCategory.Edge {
        yourBodiesInContact = false
    }
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    if yourBodiesInContact {
       // while in contact
    } else {
       // ...
    }
}