Swift / SpriteKit与自定义类碰撞

时间:2015-08-23 21:54:55

标签: ios swift sprite-kit collision

我有一个为多个SpriteNod创建变量的类,如下所示:

class Enemy {

var speed:Float = 0.0
var guy:SKSpriteNode
var currentFrame = 0
var randomFrame = 0
var moving = false
var rotationSpeed:CGFloat = 1.0
var angle = 0.0
var range = 1.2
var yPos = CGFloat()
var rotationDirection:Int = 0
var preLocation:CGFloat = 0
var health:Int = 0

init(speed:Float, guy:SKSpriteNode, rotationSpeed:CGFloat, rotationDirection:Int, preLocation:CGFloat, health:Int) {

    self.speed = speed
    self.guy = guy
    self.rotationSpeed = rotationSpeed
    self.rotationDirection = rotationDirection
    self.preLocation = preLocation
    self.health = health


}

然后将SpriteNode应用于敌人:

func addEnemy(#named: String, speed:Float, yPos: CGFloat, rotationSpeed:CGFloat, rotationDirection:Int, preLocation:CGFloat, health:Int) {

    var enemyNode = SKSpriteNode(imageNamed: named)

    enemyNode.physicsBody = SKPhysicsBody(texture: enemyNode.texture, alphaThreshold: 0, size: enemyNode.size)
    enemyNode.physicsBody!.affectedByGravity = false
    enemyNode.physicsBody!.categoryBitMask = ColliderType.Enemy.rawValue
    enemyNode.physicsBody!.contactTestBitMask = ColliderType.Hero.rawValue | ColliderType.Enemy.rawValue
    enemyNode.physicsBody!.collisionBitMask = ColliderType.Hero.rawValue | ColliderType.Enemy.rawValue
    enemyNode.physicsBody?.allowsRotation = false

    var enemy = Enemy(speed: speed, guy: enemyNode, rotationSpeed: rotationSpeed, rotationDirection: rotationDirection, preLocation: preLocation, health: health)
    enemys.append(enemy)
    enemy.guy.name = named
    resetEnemy(enemyNode, yPos: yPos)
    enemy.yPos = enemyNode.position.y
    addChild(enemyNode)

}

现在我遇到的问题是,在didBeginContact函数中我只返回SpriteNodes,这样我就无法获得敌人特定的变量,比如健康。

所以我想知道我如何将敌人类引用到spritenode,所以我可以在didBeginContact函数中使用它。

我希望有人可以帮助我。感谢。

1 个答案:

答案 0 :(得分:1)

我刚遇到了这个问题。您需要将节点强制转换为您要查找的对象。在didBeginContact中,它将是这样的:

if let myEnemy = contact.bodyA.node as? Enemy {
     myEnemy.speed = 99
}