我想生成从屏幕顶部掉落的无限数量的节点,只需点击它们即可销毁它们,这很简单,但我遇到了严重的问题。当循环生成节点时,我只能生成一个节点,它开始移动而不是垂直落下。它也会消失并不断出现。 这是我的代码,希望你能帮忙。 谢谢!!
import SpriteKit
class DestroyScene: SKScene , SKPhysicsContactDelegate{
var velocity:CGFloat = 0
let scoreText = SKLabelNode(fontNamed: "Arial Rounded MT Bold")
var score = 0
var lastYieldTimeInterval:NSTimeInterval = NSTimeInterval()
var lastUpdateTimerInterval:NSTimeInterval = NSTimeInterval()
var gameOver = false
var alien:SKSpriteNode = SKSpriteNode(imageNamed: "circuloAzulArt")
override func didMoveToView(view: SKView) {
self.physicsWorld.contactDelegate = self
self.physicsWorld.gravity = CGVectorMake(0, -velocity)
}
func addAlien(){
var alien:SKSpriteNode = SKSpriteNode(imageNamed: "circuloAzulArt")
alien.name = "alien"
alien.physicsBody = SKPhysicsBody(circleOfRadius: alien.size.width/2)
alien.physicsBody?.dynamic = true
var actionArray:NSMutableArray = NSMutableArray()
var actionArray2:NSMutableArray = NSMutableArray()
alien.removeFromParent()
if gameOver == false{
let minX = alien.size.width/2
let maxX = self.frame.size.width - alien.size.width/2
let rangeX = maxX - minX
let position:CGFloat = CGFloat(arc4random()) % CGFloat(rangeX) + CGFloat(minX)
alien.position = CGPointMake(position, self.frame.size.height + alien.size.height)
self.addChild(alien)
let minDuration = 3
let duration = Int(minDuration)
actionArray.addObject(SKAction.moveTo(CGPointMake(position, -alien.size.height), duration: NSTimeInterval(duration)))
actionArray.addObject(SKAction.removeFromParent())
alien.runAction(SKAction.sequence(actionArray))
}
}
func updateWithTimeSinceLastUpdate(timeSinceLastUpdate:CFTimeInterval){
var randomNum = Double(arc4random_uniform(20))
var xTime = ((randomNum / 20) + 0.25)
lastYieldTimeInterval += timeSinceLastUpdate
if (lastYieldTimeInterval > xTime){
lastYieldTimeInterval = 0
randomNum = Double(arc4random_uniform(25))
addAlien()
}
}
override func update(currentTime: CFTimeInterval) {
var timeSinceLastUpdate = currentTime - lastUpdateTimerInterval
lastUpdateTimerInterval = currentTime
if score < 60{
velocity = CGFloat(score*3)
}else{
velocity = CGFloat(210)
}
if (timeSinceLastUpdate > 1){
timeSinceLastUpdate = 1/60
lastUpdateTimerInterval = currentTime
}
updateWithTimeSinceLastUpdate(timeSinceLastUpdate)
}
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if self.nodeAtPoint(location) == self.alien{
alien.removeFromParent()
score++
}
}
}
}
答案 0 :(得分:1)
每当你添加一个外星人时,你用这行代码删除最后一个外星人: alien.removeFromParent()
您必须在addAlien()函数中创建一个新的变量节点,并为该节点命名
例如:
var alien:SKSpriteNode = SKSpriteNode(imageNamed: "alien")
alien.name = "alien"
然后你可以通过检查节点名称
来删除touchesBegan函数中的外星人let node = self.nodeAtPoint(location)
if (node.name == "alien") {
}
对于引力,您应该将self.physicsWorld.gravity = CGVectorMake(0, -velocity)
移动到didMoveToView()函数并将最后一个参数更改为常量