SKSpriteNode加了一次,但是出现了莫名其妙,加了六次
Posted
技术标签:
【中文标题】SKSpriteNode加了一次,但是出现了莫名其妙,加了六次【英文标题】:SKSpriteNode was added once, but it appeared a baffling, six times 【发布时间】:2016-02-18 02:36:32 【问题描述】:我只在我的动作块中添加了一次 SKSpriteNode,子弹,但不知何故,它导致六个不同的节点出现在我的模拟器中。我对我的模拟器中如何出现六个节点感到非常困惑。为什么会这样?这可能是 Xcode 中的错误吗?我删除了代码中不相关的部分,因此您不必通读所有代码。提前谢谢!
class MyScene: SKScene
var score = 0
var playerHealth = 100
var spaceShipHealth = 1000
var shooterAnimation = [SKTexture]()
var numberOfEnemies = 5
override func didMoveToView(view: SKView)
//After load, send all of the images in the atlas to the SkTexture
let shooter = self.childNodeWithName("shooter1")
shooter?.zPosition = 1
let shooterAtlas = SKTextureAtlas(named: "shooter")
for image in 1...shooterAtlas.textureNames.count
let imgName = String(format: "shooter%01d", image)
shooterAnimation += [shooterAtlas.textureNamed(imgName)]
let skActionBlock = SKAction.sequence([SKAction.runBlock(
let bullet = self.createSpaceshipBulletNode()
self.addChild(bullet)
bullet.physicsBody?.applyImpulse(CGVectorMake(-100, 0))
),SKAction.waitForDuration(3.0)])
self.runAction(SKAction.repeatAction(skActionBlock, count: numberOfEnemies))
self.physicsWorld.gravity = CGVectorMake(0, 0.2)
let bgImage = SKSpriteNode(imageNamed: "spaceBackground.jpeg")
let frameSize = self.frame.size
bgImage.size = frameSize
bgImage.position = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame))
bgImage.zPosition = 0
self.addChild(bgImage)
func createSpaceshipBulletNode() -> SKSpriteNode
let spaceShip = self.childNodeWithName("Spaceship")
let bulletX:CGFloat! = (spaceShip?.position.x)! - 200
let bulletY:CGFloat! = spaceShip?.position.y
let sBullet = SKSpriteNode(imageNamed: "bullet.png")
sBullet.position = CGPointMake(bulletX, bulletY)
sBullet.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(50, 50))
return sBullet
【问题讨论】:
您在循环中添加项目符号 【参考方案1】:运行createSpaceshipBulletNode
的操作块重复了numberOfEnemies
次,并且该调用位于从1 到shooterAtlas.textureNames.count
的for 循环中。要么你的 for 循环运行了多次,要么你有 6 个敌人。也许您打算在循环之外添加子弹,并且只在循环中设置纹理。
for image in 1...shooterAtlas.textureNames.count
let imgName = String(format: "shooter%01d", image)
shooterAnimation += [shooterAtlas.textureNamed(imgName)]
let skActionBlock = SKAction.sequence([SKAction.runBlock(
let bullet = self.createSpaceshipBulletNode()
self.addChild(bullet)
bullet.physicsBody?.applyImpulse(CGVectorMake(-100, 0))
),SKAction.waitForDuration(3.0)])
self.runAction(SKAction.repeatAction(skActionBlock, count: numberOfEnemies))
self.physicsWorld.gravity = CGVectorMake(0, 0.2)
【讨论】:
非常感谢。我以前怎么没看到!?我的意思是只在我的 for 循环中设置我的纹理。以上是关于SKSpriteNode加了一次,但是出现了莫名其妙,加了六次的主要内容,如果未能解决你的问题,请参考以下文章
无法点击 SKSpriteNode - 未检测到触摸 ios