我正在创建一个游戏,它会产生随机敌人并将它们移动到屏幕上以供用户使用spritekit进行拍摄。我遇到的问题是检测敌人何时被触碰。我尝试了很多不同的方法,但没有任何效果。我认为我遇到的问题是每个产生的敌人都使用相同的变量。所有我真正想知道的是当触摸其中一个“敌人”精灵时我如何执行某个代码块。这是我添加敌人的功能,然后我在计时器上调用此功能来添加敌人。任何帮助将非常感激,因为我迷失和沮丧。提前致谢
func addEnemy() {
let distance = CGFloat(self.frame.size.height-150)
possibleEnemy = GKRandomSource.sharedRandom().arrayByShufflingObjects(in: possibleEnemies) as! [String]
let enemy = SKSpriteNode(imageNamed: possibleEnemies[0])
let randomEnemyPosition = GKRandomDistribution(lowestValue: 200, highestValue: Int(distance))
let position = CGFloat(randomEnemyPosition.nextInt())
enemy.isUserInteractionEnabled = true
enemy.name = "\(possibleEnemies[0])"
enemy.position = CGPoint(x:-50, y: position)
enemy.physicsBody = SKPhysicsBody(rectangleOf: enemy.size)
enemy.physicsBody?.isDynamic = true
enemy.physicsBody?.categoryBitMask = enemyCategory
enemy.physicsBody?.collisionBitMask = 0
self.addChild(enemy)
let animationDuration:TimeInterval = 6
let oscillate = SKAction.oscillation(amplitude: 30, timePeriod: 4, midPoint: enemy.position)
enemy.run(SKAction.repeatForever(oscillate))
enemy.run(SKAction.moveBy(x: size.width, y: 0, duration: 5))
var actionArray = [SKAction]()
actionArray.append(SKAction.moveTo(x: self.frame.width, duration: animationDuration))
actionArray.append(SKAction.removeFromParent())
enemy.run(SKAction.sequence(actionArray))
}
编辑:用于检测敌人是否被触摸的代码
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.location(in: self)
if enemy.contains(location) {
//Run code
}
}
}
编辑:尝试检测节点是否被触摸的其他方法
let touch:UITouch = touches.anyObject()! as UITouch
let positionInScene = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(positionInScene)
if let name = touchedNode.name
{
if name == "enemy"
{
//Run code
}
}
}