我正在制作一个游戏,其中块(敌人)被硬编码为y值500并具有随机x值。我有两个块,一个是SKSpriteNode,另一个是SKSpriteNode的副本,每个块都有自己的函数,addEnemy()和addEnemyCopy()
当我运行游戏时,我看到块正在以不同的y值生成,即使它们都被硬编码为值为500.我打印出两个块的位置,我看到有时两个块正在产生的价值为500,有时它们的产生价值约为400或300.为什么会发生这种情况?我将y值设置为500,因此块应始终在y轴上产生500,然后在x轴上以随机值产生。两个块都以随机X值产生,这样部分工作正常,我确实知道有时块会在屏幕上产生,但现在忽略它。
以下是相关的代码:
原始敌人功能:
func addEnemy() {
enemy.position = CGPoint(x: CGFloat(arc4random() % UInt32(size.width - enemy.size.width)), y: 500)
print("Enemy position: ")
print(enemy.position)
enemy.zPosition = 1
enemy.setScale(0.4)
enemy.physicsBody = SKPhysicsBody(texture: enemy.texture!, size: enemy.size)
enemy.physicsBody?.affectedByGravity = false
enemy.physicsBody?.categoryBitMask = 1
enemy.physicsBody?.collisionBitMask = 0
enemy.physicsBody?.contactTestBitMask = 2
self.addChild(enemy)
let moveEnemy = SKAction.moveTo(y: player.position.y - 300, duration: 1)
let deleteEnemy = SKAction.removeFromParent()
let enemySequence = SKAction.sequence([moveEnemy, deleteEnemy])
enemy.run(enemySequence,
completion: {
if self.playerLost == false {
if self.score >= 1 {
self.enemy.removeFromParent()
self.scoreLabel.removeFromParent()
self.score += 1
self.setScore()
self.addEnemy()
} else {
self.score += 1
self.setScore()
self.enemy.removeFromParent()
self.addEnemy()
}
}
}
)
}
复制敌人的功能:
func addEnemyCopy() {
let enemyCopy = enemy.copy() as! SKSpriteNode
enemy.position = CGPoint(x: CGFloat(arc4random() % UInt32(size.width - (enemy.size.width + 100))), y: 500)
print("Enemy copy: ")
print(enemyCopy.position)
self.addChild(enemyCopy)
let moveEnemy1 = SKAction.moveTo(y: player.position.y - 300, duration: 1)
let deleteEnemy1 = SKAction.removeFromParent()
let enemySequence1 = SKAction.sequence([moveEnemy1, deleteEnemy1])
enemyCopy.run(enemySequence1,
completion: {
if self.playerLost == false {
if self.score >= 1 {
enemyCopy.removeFromParent()
self.scoreLabel.removeFromParent()
self.setScore()
self.addEnemyCopy()
} else {
self.setScore()
self.addEnemyCopy()
}
}
}
)
}
不确定我应该放在这里的其他代码,或者我是否应该全部放入。请随时在评论中询问以显示更多代码。
谢谢!我知道我总是可以指望Stack Overflow来帮助我!
答案 0 :(得分:1)
复制并粘贴失败:
func addEnemyCopy() {
let enemyCopy = enemy.copy() as! SKSpriteNode
****enemyCopy.position = CGPoint(x: CGFloat(arc4random() % UInt32(size.width - (enemy.size.width + 100))), y: 500)***
print("Enemy copy: ")
print(enemyCopy.position)
self.addChild(enemyCopy)
let moveEnemy1 = SKAction.moveTo(y: player.position.y - 300, duration: 1)
let deleteEnemy1 = SKAction.removeFromParent()
let enemySequence1 = SKAction.sequence([moveEnemy1, deleteEnemy1])
enemyCopy.run(enemySequence1,
completion: {
if self.playerLost == false {
if self.score >= 1 {
enemyCopy.removeFromParent()
self.scoreLabel.removeFromParent()
self.setScore()
self.addEnemyCopy()
} else {
self.setScore()
self.addEnemyCopy()
}
}
}
)
}
我建议更频繁地使用refactor
。也就是说,如果重命名1个变量,它会将该变量重命名为附加到该声明的任何位置。