Reputation: 1177
I am working on a 2D game, and I'm using the Swift and SpriteKit. To begin, I started creating animated objects and moving to down. To create these "objects", I used the Spaceship (Asset image of Xcode).
See my code:
import SpriteKit
class GameScene: SKScene {
var spaceship = SKSpriteNode()
var screenSize:CGSize!
var gameStarted:Bool = false
var moveAndRemove = SKAction()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
screenSize = self.frame.size
self.createSpaceship()
}
func createSpaceship() -> Void {
spaceship = SKSpriteNode()
spaceship.texture = SKTexture(imageNamed: "Spaceship")
spaceship.size = CGSize(width: 70, height: 100)
spaceship.setScale(1.0)
spaceship.position = CGPoint(x: screenSize.width / 3, y: screenSize.height - 75)
spaceship.zPosition = 1
self.addChild(spaceship)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if gameStarted == false {
gameStarted = true
let spawn = SKAction.runBlock { () in
self.createSpaceship()
}
let delay = SKAction.waitForDuration(1.5)
let spawnDelay = SKAction.sequence([spawn, delay])
let spanDelayForever = SKAction.repeatActionForever(spawnDelay)
self.runAction(spanDelayForever)
let distance = CGFloat(screenSize.height + spaceship.frame.height)
let moveTargets = SKAction.moveToY(spaceship.frame.origin.y - distance, duration: 8.0)
let removeTargets = SKAction.removeFromParent()
moveAndRemove = SKAction.sequence([moveTargets,removeTargets])
}
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
}
}
But when I run the game, Spaceship stands still on display. I can not find it can solve.
Can someone help me?
The Spaceship have to go down (Y), create copies, and move to down in Y.
Upvotes: 0
Views: 1883
Reputation: 12753
You need to run the moveAndRemove
action on each spaceship. I suggest you move the action definition to the createSpaceship
method and run the moveAndRemove
action on each spaceship that you create. For example,
func createSpaceship() {
// This can be a local variable and combined into a single statement
let spaceship = SKSpriteNode(imageNamed: "Spaceship")
spaceship.size = CGSize(width: 70, height: 100)
spaceship.setScale(1.0)
spaceship.position = CGPoint(x: screenSize.width / 3, y: screenSize.height - 75)
spaceship.zPosition = 1
let distance = CGFloat(screenSize.height + spaceship.frame.height)
let moveTargets = SKAction.moveToY(spaceship.frame.origin.y - distance, duration: 8.0)
let removeTargets = SKAction.removeFromParent()
let moveAndRemove = SKAction.sequence([moveTargets,removeTargets])
// Add the action to the list of actions executed by the spaceship
spaceship.runAction(moveAndRemove)
self.addChild(spaceship)
}
Upvotes: 3