如何告诉Sprite Kit运行哪个函数?

时间:2015-03-13 20:35:34

标签: ios swift sprite-kit

我有四个敌人。对于每个敌人,我都有一个运行动画的功能。英雄如果触及敌人就会死亡。基本上,我需要对一个程序说:如果英雄触及那个敌人,那么运行该功能。如果它触及另一个 - 运行另一个功能。这有多难,对吧?但我现在已经把头发拉了两天,因为我不能这样做。这是我的ColliderType:

enum ColliderType:UInt32 {
    case Cookie = 1
    case Rabbit = 2
    case Mouse = 3
    case Hamster = 4
    case Cat = 5
}

这些是他们的物理实体(这是一个样本,而不是整个代码):

self.cookie.physicsBody = SKPhysicsBody(circleOfRadius: CGFloat(self.cookie.size.width / 2))
self.cookie.physicsBody?.affectedByGravity = false
self.cookie.physicsBody?.categoryBitMask = ColliderType.Cookie.rawValue
self.cookie.physicsBody?.collisionBitMask = ColliderType.Mouse.rawValue
self.cookie.physicsBody?.contactTestBitMask = ColliderType.Mouse.rawValue

self.mouse.physicsBody = SKPhysicsBody(rectangleOfSize: self.mouse.size)
self.mouse.physicsBody?.dynamic = false
self.mouse.physicsBody?.categoryBitMask = ColliderType.Mouse.rawValue
self.mouse.physicsBody?.contactTestBitMask = ColliderType.Cookie.rawValue
self.mouse.physicsBody?.collisionBitMask = ColliderType.Cookie.rawValue    

这是我运行动画的功能之一:

func eatenByMouse() {
    self.groundSpeed = 0
    self.cookie.hidden = true
 let animateAction = SKAction.animateWithTextures(self.mouseArray, timePerFrame: 0.1)
    self.mouse.runAction(animateAction)
}

这是didBeginContact:

func didBeginContact(contact: SKPhysicsContact) {
    dead()
}

我完全不知道在“死”功能中存储什么。请帮助我,我尝试了所有我知道的事情。

2 个答案:

答案 0 :(得分:0)

contact方法中的变量didBeginContact会返回您需要的相应信息。你需要得到两个体变量并比较它们的categoryBitMask,然后调用动画选择的方法。

func didBeginContact(contact: SKPhysicsContact) {

    var firstBody: SKPhysicsBody
    var secondBody: SKPhysicsBody
    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {
        firstBody = contact.bodyA
        secondBody = contact.bodyB
    } else {
        firstBody = contact.bodyB
        secondBody = contact.bodyA
    }

   if (firstBody.categoryBitMask == ColliderType.Cookie.toRaw() &&
       secondBody.categoryBitMask == ColliderType.Mouse.toRaw()) {
       eatenByMouse()
   }
   if (firstBody.categoryBitMask == ColliderType.Cookie.toRaw() &&
       secondBody.categoryBitMask == ColliderType.Rabbit.toRaw()) {
       eatenByRabbit()
   }
}

答案 1 :(得分:0)

这些建议对我不起作用。因此,对于有类似问题的人,我决定发布有效的代码:

func didBeginContact(contact: SKPhysicsContact) {
    if (contact.bodyA.categoryBitMask == ColliderType.Mouse.rawValue || contact.bodyB.categoryBitMask == ColliderType.Mouse.rawValue) {
        eatenByMouse()
    }
    if (contact.bodyA.categoryBitMask == ColliderType.Rabbit.rawValue || contact.bodyB.categoryBitMask == ColliderType.Rabbit.rawValue) {
        eatenByRabbit()
    }