我正在努力解决一个问题。我的精灵的全局声明,以便我可以与其进行交互。在这个游戏中,我创建了一个名为敌人的本地精灵,如下所示:
func spawnEnemy() {
let enemy = SKSpriteNode(imageNamed: "as")
let yPosition = CGFloat(frame.maxY - enemy.size.height)
let getXvalue = GKRandomDistribution(lowestValue: Int(frame.minX + enemy.size.width), highestValue: Int(frame.maxX - enemy.size.width))
let xPosition = CGFloat(getXvalue.nextInt())
enemy.position = CGPoint(x: xPosition, y: yPosition)
enemy.name = "asteroid"
enemy.zPosition = 100
addChild(enemy)
let animationDuration:TimeInterval = 6
var actionArray = [SKAction]()
actionArray.append(SKAction.move(to: CGPoint(x: xPosition, y: 0), duration: animationDuration))
actionArray.append(SKAction.self.removeFromParent())
enemy.run(SKAction.sequence(actionArray))
}
我想点击敌人使其从屏幕上消失。该变量在本地而不是全局声明,因此touchesBegan函数不会“看到”敌人。但是,当我移动语句时:
let enemy = SKSpriteNode(imageNamed: "as")
在本地声明之外并进入全局。在代码尝试生成另一个敌人之前,它会一直起作用,直到出现错误“试图添加已经有父级的SKNode”,这是我在视图中运行的代码已加载的内容:
run(SKAction.repeatForever(SKAction.sequence([SKAction.run{self.spawnEnemy()
}, SKAction.wait(forDuration: 1.0)])))
每当它产生一个新的敌人时,它就会崩溃并说SKNode已经有一个我了解的父级。但是,为了使我的游戏正常运行,我需要玩家能够触摸该敌人的单个实例并将其移除。因此,我的
代码override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let location = touch?.location(in:self) {
let nodesArray = self.nodes(at:location)
if nodesArray.first?.name == "asteroid" {
print("Test")
enemy.removeFromParent()
print("Test Completed")
}
}
}
现在错误提示未解决的“敌人”用法,因为敌人不在全球范围内。我已经在这个问题上来回反复了一段时间。如果有人有任何潜在的解决方案或解决方法,我将非常感谢,感谢您的帮助。
答案 0 :(得分:0)
将您的敌人移到自己的班上,并为自己班上的每个敌人处理碰触。这将清理您的GameScene,并使您的代码更有条理。现在,您可以根据需要添加任意数量的敌人实例。
仅供参考,与您有关的问题
尝试将尽可能多的代码分离到您的对象类中
class enemy: SKSpriteNode {
init() {
super.init(texture: nil, color: .clear, size: CGSize.zero)
setup()
}
func setup() {
isUserInteractionEnabled = true
name = "asteroid"
zPosition = 100
let image = SKSpriteNode(imageNamed: "as")
imagine.zPosition = 1
addChild(image)
self.size = image.size
animate()
}
func animate() {
let animationDuration: TimeInterval = 6
let move = SKAction.move(to: CGPoint(x: xPosition, y: 0), duration: animationDuration)
let remover = SKAction.self.removeFromParent()
run(SKAction.sequence(move, remover))
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
removeFromParent()
}
}
class GameScene: SKScene {
override func didMove(to view: SKView) {
let sequence = SKAction.sequence([SKAction.run{ self.spawnEnemy()
}, SKAction.wait(forDuration: 1.0)])
run(SKAction.repeatForever(sequence))
}
func spawnEnemy() {
let enemy = Enemy()
let yPosition = CGFloat(frame.maxY - enemy.size.height)
let getXvalue = GKRandomDistribution(lowestValue: Int(frame.minX + enemy.size.width), highestValue: Int(frame.maxX - enemy.size.width))
let xPosition = CGFloat(getXvalue.nextInt())
enemy.position = CGPoint(x: xPosition, y: yPosition)
addChild(enemy)
}
}