我在屏幕上有多个敌人节点,我有一个十字准线用于瞄准和触摸任何地方拍摄&杀死敌人。我设法检测到十字准线何时瞄准敌人,但是当我触摸屏幕以影响这个特定的敌人时我无法管理。
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 == CrosshairCategory && secondBody.categoryBitMask == EnemyCategory {
canShoot = true
}
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
}
}
每个敌人都是一个子类的实例,它拥有自己的健康和行为。现在我怎样才能从接触函数中获取特定的敌人,这样我就可以在touchesbegan函数中影响它?
func createEnemy(sprite: String, position: CGPoint, name: String) {
monster = Enemy(imageNamed: sprite)
monster.position = position
monster.name = name
monster.size = CGSizeMake(56, 35)
monster.physicsBody = SKPhysicsBody(circleOfRadius: monster.size.width / 2)
monster.physicsBody?.categoryBitMask = EnemyCategory
monster.physicsBody?.contactTestBitMask = CrosshairCategory
monster.physicsBody?.collisionBitMask = 0
monster.moveEnemy()
monster.createHealth()
addChild(monster)
}
override func didMoveToView(view: SKView) {
createEnemy(enemyNode, position: CGPointMake(20, 200), name: "enemy1")
createEnemy(blueStand, position: CGPointMake(20, 400), name: "enemy2")
}
我正在考虑创建几个实例,比如(monster1 - monster2),而不是使用didMoveToView中的函数调用来创建它们,然后我可以在touchesbegan函数中轻松引用它们,但我不知道这是不是最有效的方式。
我希望我对我的问题已经足够清楚了:))
更新
touchesBegan(touches: NSSet, withEvent event: UIEvent) {
if canShoot {
(secondBody.node as Enemy).healthPoints -= 20
(secondBody.node as Enemy).removeAllChildren()
(secondBody.node as Enemy).createHealth()
}
Enemy.swift
class Enemy: SKSpriteNode {
var healthPoints: CGFloat = 60
var redBar = SKSpriteNode()
func createHealth() {
if healthPoints <= 0 {
self.removeFromParent()
} else {
redBar = SKSpriteNode(color: UIColor.redColor(), size: CGSizeMake(healthPoints, 5))
redBar.position = CGPointMake(0, 30)
self.addChild(redBar)
}
}
func moveEnemy() {
//some code
}
它现在工作正常,但我只能杀死我创建的第一个怪物(又名healthPoints = 0)然后我得到一个错误&#34;致命错误:在解开一个可选值时意外发现nil&#34;虽然试图杀死不止一个,意味着只有一个怪物表现得应该然后我得到错误,非常奇怪。