Swift/SpriteKit 与自定义冲突 Class

Swift/SpriteKit Collision with Custom Class

我有一个 class 可以为多个 SpriteNods 创建变量,如下所示:

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 应用于 Enemy:

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 函数中,我只能返回 SpriteNode,所以我无法获取敌人特定的变量,例如生命值。

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

我希望有人能帮助我。谢谢

我刚刚 运行 解决了这个问题。您需要将节点转换为您要查找的对象。在 didBeginContact 中,它将是这样的:

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