I was wondering if someone could show me how to make it so that I can spawn random image missiles. Right now I am using one image called "meteor", I have a few more images I would like to show and randomize. I know I need to put them in an array and create an arc for random. I have done it for sound but I'm not sure how to do it for images. This is my code so far.
var lastMissileAdded : NSTimeInterval = 0.0
let missileVelocity : CGFloat = 4.0
func addMissile() {
// Initializing missile node
var missile = SKSpriteNode(imageNamed: "meteor")
missile.setScale(0.44)
// Adding SpriteKit physics body for collision detection
missile.physicsBody = SKPhysicsBody(rectangleOfSize: missile.size)
missile.physicsBody?.categoryBitMask = UInt32(obstacleCategory)
missile.physicsBody?.dynamic = true
missile.physicsBody?.contactTestBitMask = UInt32(shipCategory)
missile.physicsBody?.collisionBitMask = 0
missile.physicsBody?.usesPreciseCollisionDetection = true
missile.name = "missile"
// Selecting random y position for missile
var random : CGFloat = CGFloat(arc4random_uniform(300))
missile.position = CGPointMake(self.frame.size.width + 20, random - 20)
self.addChild(missile)
}
func moveObstacle() {
self.enumerateChildNodesWithName("missile", usingBlock: { (node, stop) -> Void in
if let obstacle = node as? SKSpriteNode {
obstacle.position = CGPoint(x: obstacle.position.x - self.missileVelocity, y: obstacle.position.y)
if obstacle.position.x < 0 {
obstacle.removeFromParent()
}
}
})
}
All you need to do is name them meteor0, meteor1 and meteor2 and use String Interpolation to create your node with your random image:
var missile = SKSpriteNode(imageNamed: "meteor\(arc4random_uniform(3))")
Related
I'm in the process of creating a card game in Swift using SKSprite Nodes to show the card faces.
In my 'deal' function, it deals 3 cards to each player, one at a time in a 'round-robin' fashion. This is working fine but I'm trying to add a bit of animation - I'm trying to make it show each card being dealt to the local player by animating it moving from the deck to the players hand position.
I can get the Sprite Nodes to show without the animation but when I try with SKAction, it gives me the following error after the action is completed:
reason: 'Attemped to add a SKNode which already has a parent: name:'local player node' texture:[ 'CARD39' (203 x 350)] position:{281.25, 100.05000305175781}
class GameScene: SKScene {
let tempCard = SKSpriteNode(texture: SKTexture(imageNamed: "back"))
func deal() {
players = createPlayers(with: numberOfPlayers)
tempCard.setScale((screenSize.width/100) * 0.2)
tempCard.zPosition = 10
tempCard.name = "tempcard"
addChild(tempCard)
let localPlayer = 0
var i = 0
repeat {
print("Card number: \(i)")
var x = 0
let xPos = screenSize.width * (0.25 * CGFloat(i+1))
players.forEach { player in
let newCard = self.deck.dealOneCard()
player.hand.addCard(card: newCard)
localPlayerNode = players[localPlayer].hand[i].cardImage()
localPlayerNode.position = CGPoint(x: xPos, y: screenSize.height * 0.15)
localPlayerNode.setScale((screenSize.width/100) * 0.2)
localPlayerNode.name = "local player node"
if player.id == localPlayer {
let moveCard = SKAction.move(to: CGPoint(x: xPos, y: screenSize.height * 0.15),duration: 1.5)
//addChild(localPlayerNode) --using this instead of SKAction works
tempCard.run(moveCard, completion: {() -> Void in
self.tempCard.removeFromParent()
self.addChild(self.localPlayerNode)
})
}
x+=1
}
i+=1
} while i<3
I believe the problem is with adding the player nodes within your loop, and then not removing them afterwards. I'm sure you don't want to remove the players every time you call the " deal() " function so you should add the player nodes in the didMove() method.
I've put together a playground that demonstrates this (github Link).
I've tried to use a delay to make the cards deal 1 by one, but this is a different problem you will need to look elsewhere to solve. (Something with the .run( action) makes it so that it doesn't actually animate until the loop is complete.
example gif with bad pixel art
class GameScene: SKScene {
let scale : CGFloat = 50
var deck : [String] = []
let composition = deckComp()
let numberOfPlayers = 3
var players : [Player] = []
override func didMove(to view: SKView) {
// creates deck
for c in deckComp().colors {
for s in deckComp().suits {
deck.append( s + " of " + c )
}
}
players = createPlayers(numberOfPlayers: numberOfPlayers, center : CGPoint(x : 25, y : 25))
// setup the scales, and players
for plyr in players {
plyr.setScale(scale: (frame.width/10000) * scale)
addChild( plyr.node)
}
}
func createPlayers(numberOfPlayers : Int, center : CGPoint) -> [Player] {
let radius = Float(5*scale)
let two_pi = 2 * 3.14159
let angular_positions = two_pi / Double(numberOfPlayers)
var players_out : [Player] = []
for i in 0...numberOfPlayers - 1 {
let sprite = SKSpriteNode(texture: SKTexture(imageNamed: "card_player.png"))
sprite.zPosition = 1
sprite.position = CGPoint( x : center.x + CGFloat(radius * sin( Float(angular_positions) * Float(i) )), y : center.y + CGFloat(radius * cos( Float(angular_positions) * Float(i) )) )
sprite.texture?.filteringMode = .nearest // .linear for blurry, .nearest for pixely
let player_instance = Player(node : sprite, name : "Player " + String(i + 1), id : Int8(i + 1) )
players_out.append(player_instance)
}
return players_out
}
func deal() {
// I moved the setscale stuff for player sprites to didMove()
// first check if there is enough in deck
if deck.count > players.count {
var i = 0
repeat {
// add the temp card
let tempCard = SKSpriteNode(texture: SKTexture(imageNamed: "back"))
tempCard.size = CGSize( width: tempCard.size.width * (frame.width/10000) * scale, height : tempCard.size.height * (frame.width/10000) * scale )
tempCard.zPosition = 10
tempCard.texture?.filteringMode = .nearest
self.addChild(tempCard)
// done adding temporary card
let xPos = frame.width * (0.25 * CGFloat(i+1))
tempCard.position = CGPoint(x : xPos, y : 0.75 * frame.height)
let newCard = self.deck.popLast() // replaced dealOneCard() since I haven't defined it
players[i].addCard(card: newCard!) // removed hand.addCard(), since I don't have the array extensions
// player.name = "local player node"
let moveCard = SKAction.move(to: players[i].node.position ,duration: 1.5)
//addChild(localPlayerNode) --using this instead of SKAction works
tempCard.run(moveCard, completion: { () -> Void in tempCard.removeFromParent(); })
i += 1
} while i < players.count
} else { print("not enough cards to deal to everyone")} // when deck is empty
}
override func mouseUp(with event: NSEvent) {
deal()
}
I am building a maze and I have added some SKSpritekit nodes for the walls and a dot for the player. however when the dot and the walls collide, there is no detection of collision. my code is as follows:
import UIKit
import SpriteKit
import GameplayKit
import Foundation
import GameplayKit
class level1: SKScene, SKPhysicsContactDelegate {
var entities = [GKEntity]()
var graphs = [String : GKGraph]()
var dot = SKSpriteNode()
override func sceneDidLoad () {
buildMaze()
addDot()
func addDot() {
let startNum = x * (y - 1)
startCoord = coordArray[startNum]
dot = SKSpriteNode(imageNamed: "redDot")
dot.physicsBody?.isDynamic = true
dot.size = CGSize(width: 20, height: 20)
dot.position = startCoord
dot.physicsBody = SKPhysicsBody(circleOfRadius: 10)
dot.physicsBody?.mass = 0
dot.physicsBody?.usesPreciseCollisionDetection = true
self.addChild(dot)
}
func buildMaze() {
let difference = coordArray[1].x - coordArray[0].x
let wallDistance = difference/2
let thickness = CGFloat(3)
let length = difference - CGFloat(thickness)/2
var count = 0
for point in coordArray {
let northWall = SKSpriteNode(color: SKColor.black, size : CGSize (width: length, height: thickness))
northWall.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: length, height: thickness))
northWall.physicsBody?.mass = 200000
let southWall = SKSpriteNode(color: SKColor.black, size : CGSize (width: length, height: thickness))
southWall.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: length, height: thickness))
southWall.physicsBody?.mass = 200000
let eastWall = SKSpriteNode(color: SKColor.black, size : CGSize (width: thickness, height: length ))
eastWall.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: thickness, height: length))
eastWall.physicsBody?.mass = 200000
let westWall = SKSpriteNode(color: SKColor.black, size : CGSize (width: thickness, height: length ))
westWall.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: thickness, height: length))
westWall.physicsBody?.mass = 200000
if !instructions[count].contains("N") {
//print("added north wall")
northWall.position = CGPoint (x: point.x , y: point.y + wallDistance)
if nodes(at: northWall.position) == [] {
addChild(northWall)}
else {print("north wall already there")}
}
if !instructions[count].contains("S") {
//print("added south wall")
southWall.position = CGPoint (x: point.x , y: point.y - wallDistance)
if nodes(at: southWall.position) == [] {
addChild(southWall)}
else {//print("southwall already there")
}
}
if !instructions[count].contains("E") {
//print("added east wall")
eastWall.position = CGPoint (x: point.x + wallDistance , y: point.y)
if nodes(at: eastWall.position) == [] {
addChild(eastWall)}
else {//print("east already there")
}
}
if !instructions[count].contains("W") {
//print("added west wall")
westWall.position = CGPoint (x: point.x - wallDistance , y: point.y)
if nodes(at: westWall.position) == [] {
addChild(westWall)}
else {//print("west wall already there")
}
}
count = count + 1
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for t in touches {
let location = t.location(in: self)
dot.position.x = location.x
dot.position.y = location.y
}
}
func didBegin(_ contact: SKPhysicsContact) {
print("contact!")
}
The walls appear just as I wanted them, and the dot is also in the right position.
I added a masso of 20000 for each of them so that when I move the dot, the walls stay in place. however, when I move the dot with my finger, it just goest straight through the walls of the maze instead of being stopped by them.
I added a print statement to the didBegin function to see if at least it was detecting any contact between the sprites, but it does not.
Why is this?
cheers!
First in your didMoveTo or sceneDidLoad, you need to set the physicsContactDelegate:
override func sceneDidLoad () {
physicsWorld.contactDelegate = self
buildMaze()
addDot()
}
To set the contact/collision mask, you have to do it this way, because they're based on bitwise operation:
Let's suppose you want collision between dot and walls
struct PhysicsCategory {
static let wall: UInt32 = 0x1 << 1
static let dot: UInt32 = 0x1 << 2
}
You can put the struct above you class if you want
Then, when you assign physics body, you have to set the bitmask:
For dots:
dot.physicsBody?.categoryBitMask = PhysicsCategory.dot
dot.physicsBody?.contactTestBitMask = PhysicsCategory.wall
dot.physicsBody?.collisionBitMask = PhysicsCategory.wall
//Collision is different from contact, so if you want to avoid collision
//dot.physicsBody?.collisionBitMask = PhysicsCategory.dot
Collision is different from contact, check apple documentation about it
For walls:
northWall.physicsBody?.categoryBitMask = PhysicsCategory.wall
northWall.physicsBody?.contactTestBitMask = PhysicsCategory.dot
northWall.physicsBody?.collisionBitMask = PhysicsCategory.dot
//Do the same for all walls
If you want walls to contact or collide with more than one object:
northWall.physicsBody?.contactTestBitMask = PhysicsCategory.dot | PhysicsCategory.other
northWall.physicsBody?.collisionBitMask = PhysicsCategory.dot | PhysicsCategory.other
For walls are valid all consideration as per dots
Collision and contact detection don't work very well when you set the position of your sprites directly.
In your code, the lines:
dot.position.x = location.x
dot.position.y = location.y
are directly setting the position of dot, overriding anything that the physics engine wants to do with the objects.
Also, you don't appear to have set up any of the necessary categories or collision/contactTest bit masks.
You allow manual movement of the dot but with contact detection with the walls, then you'd probably need to see if the touch onthe screen was inside a wall and then not move the dot if that was the case. (which would mean that you are not using physics at all).
Edit: my step-by-step guide for collisions and contacts:
https://stackoverflow.com/a/51041474/1430420
And a guide to collision and contactTest bit masks:
https://stackoverflow.com/a/40596890/1430420
I want the pacman to restart from its original position when it collides with blinky, that is moving.
How can I make them collide considering I have already declared them?
You move the pacman, but blinky moves alone. I want it to work like the pacman game.
public class PacmanScene: SKScene {
let playerSpeed: CGFloat = 40.0
var pacman: SKSpriteNode?
var playerTextures: [SKTexture] = []
var lastTouch: CGPoint? = nil
var blinky: SKSpriteNode?
var clyde: SKSpriteNode?
var inky: SKSpriteNode?
var pinky: SKSpriteNode?
override public init(size: CGSize) {
let pacmanTexture = SKTexture(imageNamed: "pacman01.png")
pacman = SKSpriteNode(texture: pacmanTexture)
pacman?.name = "pacman"
pacman?.position = CGPoint(x:30, y:30)
pacman?.zPosition = 1.0
pacman?.physicsBody = SKPhysicsBody(texture: pacmanTexture, size: CGSize(width: (pacman?.size.width)!, height: (pacman?.size.height)!))
pacman?.physicsBody?.allowsRotation = true
pacman?.physicsBody?.affectedByGravity = false
pacman?.physicsBody?.mass = 2
let blinkyTexture = SKTexture(imageNamed: "blinky.png")
blinky = SKSpriteNode(texture: blinkyTexture)
blinky?.name = "blinky"
blinky?.position = CGPoint(x: 15, y: 60)
blinky?.zPosition = 1.0
blinky?.physicsBody = SKPhysicsBody(texture: pacmanTexture, size: CGSize(width: (blinky?.size.width)!, height: (blinky?.size.height)!))
blinky?.physicsBody?.allowsRotation = false
blinky?.physicsBody?.affectedByGravity = false
blinky?.physicsBody?.mass = 1000
super.init(size: size)
addChild(pacman!)
addChild(blinky!)
override public func didMove(to view: SKView) {
let bmoveUp = SKAction.moveBy(x: 0, y: 450, duration: 4.0)
let bmoveRight = SKAction.moveBy(x:20, y:0, duration: 1.0)
let bmoveDown = SKAction.moveBy(x:0, y: -450, duration: 4.0)
let bmoveLeft = SKAction.moveBy(x:-20, y:0, duration: 1.0)
let bsequence = SKAction.sequence([bmoveUp, bmoveRight, bmoveDown, bmoveLeft])
let bendlessAction = SKAction.repeatForever(bsequence)
blinky?.run(bendlessAction)
}
If iv got this right you want your "blinky" to follow your "pacman" to do this you would have to work out the position of the pacman then add an SKAction to your blinky to move to that position.
Try something like this
//Speed blinky moves
let blinkySpeed = 100
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
updateBlinky()
}
func updateBlinky() {
//Set the point that blinky moves to
let point = CGPoint(x: pacman.position.x, y: pacman.position.y)
//Get the distance its got to travel
let distance = distanceBetweenPoints(first: pacman.position, second: blinky.position)
//Get the time is got to take from the speed and distance
let time = distance / blinkySpeed
//Create and run the action
let action = SKAction.move(to: point, duration: TimeInterval(time))
blinky.run(action)
}
//work out the distance between the sprites
func distanceBetweenPoints(first: CGPoint, second: CGPoint) -> Int {
return Int(hypot(second.x - first.x, second.y - first.y))
}
The end result would be something like this
Edit:
Okay I think from your question you already have "blinky" moving you just want to detect collisions.
First you need to add the SKPhysicsContactDelegate to your class
public class PacmanScene: SKScene, SKPhysicsContactDelegate {
Then you need to add a category bit mask to both the sprites then handle the collisions in didBegin(_ contact: SKPhysicsContact) method.
What I would do
//Create Physics category struct
struct PhysicsCategory {
static let pacman : UInt32 = 0x1 << 1
static var blinky : UInt32 = 0x1 << 2
}
Then where you are setting up pacman and blinky set the category bitmask
//Set the category bit mask for pacman
pacman?.physicsBody?.categoryBitMask = PhysicsCategory.pacman
//Set what categories you want to test contact
pacman?.physicsBody?.contactTestBitMask = PhysicsCategory.blinky
//Set what categories you want to collide with each other
pacman?.physicsBody?.collisionBitMask = PhysicsCategory.blinky
//Set the category bit mask for blinky
blinky?.physicsBody?.categoryBitMask = PhysicsCategory.blinky
//Set what categories you want to test contact
blinky?.physicsBody?.contactTestBitMask = PhysicsCategory.pacman
//Set what categories you want to collide with each other
blinky?.physicsBody?.collisionBitMask = PhysicsCategory.pacman
Then you would need to implement the didBegin(_ contact: SKPhysicsContact) method to handle the collisions
func didBegin(_ contact: SKPhysicsContact) {
//Work out which contact was pacman
let other = contact.bodyA.categoryBitMask == PhysicsCategory.pacman ? contact.bodyB : contact.bodyA
//Test what it hit
switch other.categoryBitMask {
case PhysicsCategory.blinky:
print("pacman hit blinky")
//Move pacman
pacman?.position = CGPoint(x:30, y:30)
default:
break
}
}
Hope this helps
I have a ios 9 spritekit game. I am adding a i-beam or a wrecking ball that should swing from a jointed rope like a pendulum. My game requires gravity and I want the beam to react to gravity and sprites that jump on the beam or hit the beam from below. When I use the following code, the beam eventually slows down and comes to rest without any interaction with other sprites. The top node in the jointed node is fixed (i.e., modeling attachment to a crane or building) I start the beam swinging by applying an impulse on the bottom node in the jointed node. I have set the friction, linear dampening, and angular dampening to 0.
What I need the beam to do prior to interacting with any sprites is to swing back and forth where the maximum height on the left swing and right swing is nearly the same throughout time. I want the beam or wrecking ball to act like its swinging from a frictionless pivot. The beam or ball doesn't go in a full circle, so I cannot use a constant angular velocity.
I tried something similar to:
Constant speed orbit around point with SKNode but neither the linear nor angular velocity is constant after the initial impulse as the beam or ball will arc up, slow down, stop at the top of the arc, and then circle back in the other direction.
let (actionSceneObjectNode, jointArray) = ActionSceneObject.createActionJointedSceneObjectAtPosition(CGPoint(x: positionX, y: positionY), ofType: actionSceneObject.type!, withImage: actionSceneObject.imageName, withActionDirection: actionSceneObject.imageDirection)
foregroundNode.addChild(actionSceneObjectNode)
if let bottomNode = actionSceneObjectNode.childNodeWithName("bottomObject") {
bottomNode.physicsBody?.applyImpulse(CGVector(dx: 50000.0, dy: 0))
}
// add the joints
for joint in jointArray {
self.physicsWorld.addJoint(joint)
}
Function
class func createActionJointedSceneObjectAtPosition(position: CGPoint, ofType type: ActionSceneObjectType, withImage imageName: String, withActionDirection actionDirection: DirectionValue) -> (ActionSceneObjectNode, [SKPhysicsJoint]) {
let node = ActionSceneObjectNode()
node.position = position
node.name = SceneObjectType.Action.rawValue
node.actionType = type
node.actionDirection = actionDirection
var jointArray = [SKPhysicsJoint]()
var sprite: SKSpriteNode
////////
// adapted from https://stackoverflow.com/questions/20811931/how-to-create-a-rope-in-spritekit
let countJointElements:Int = 3
let texture = SKTexture(imageNamed: "Rope.png")
//let textureSize = CGSize(width: texture.size().width*SceneObjectSizeScale.ActionSceneObject, height: texture.size().height*SceneObjectSizeScale.ActionSceneObject)
let topAnchor = SKSpriteNode(texture: texture, size: texture.size())
topAnchor.name = "topAnchor"
//topAnchor.position = CGPointMake(position.x, position.y) // the node holds the joint start position
topAnchor.physicsBody = SKPhysicsBody(rectangleOfSize: texture.size())
topAnchor.physicsBody?.categoryBitMask = PhysicsCategoryBitmask.None
topAnchor.physicsBody?.affectedByGravity = false
topAnchor.physicsBody?.friction = 0.0
topAnchor.physicsBody?.restitution = 1.0
topAnchor.physicsBody?.linearDamping = 0.0
topAnchor.physicsBody?.angularDamping = 0.0
topAnchor.physicsBody?.mass = 10.0
node.addChild(topAnchor)
// by default, the joints build top to bottom
for index in 0 ..< countJointElements {
let item = SKSpriteNode(texture: texture, size: texture.size())
item.name = "ropeitem_" + String(index)
item.position = CGPointMake(0, 0 - CGFloat(index+1) * item.size.height)
item.physicsBody = SKPhysicsBody(rectangleOfSize: texture.size())
item.physicsBody?.categoryBitMask = PhysicsCategoryBitmask.None
item.physicsBody?.affectedByGravity = true
item.physicsBody?.friction = 0.0
item.physicsBody?.restitution = 1.0
item.physicsBody?.linearDamping = 0.0
item.physicsBody?.angularDamping = 0.0
item.physicsBody?.mass = 10.0
node.addChild(item)
var bodyA = SKPhysicsBody()
if (index == 0)
{
bodyA = topAnchor.physicsBody!;
}
else
{
let nameString = "ropeitem_" + String(index - 1)
let nodeItem = node.childNodeWithName(nameString) as! SKSpriteNode
bodyA = nodeItem.physicsBody!
}
// needs to in terms of the physics world - the item position in the node is already negative
let joint = SKPhysicsJointPin.jointWithBodyA(bodyA, bodyB: item.physicsBody!, anchor: CGPointMake(position.x, position.y + item.position.y + item.size.height/2))
jointArray.append(joint)
}
let nameString = NSString(format: "ropeitem_%d", countJointElements - 1)
let lastLinkItem = node.childNodeWithName(nameString as String)
let bottomObject = SKSpriteNode(imageNamed: "I-Beam.png")
bottomObject.name = "bottomObject"
bottomObject.setScale(SceneObjectSizeScale.Platform)
bottomObject.position = CGPointMake(0, 0 + lastLinkItem!.position.y - lastLinkItem!.frame.size.height/2.0 - bottomObject.frame.size.height/2.0)
bottomObject.physicsBody = SKPhysicsBody(rectangleOfSize: bottomObject.size)
bottomObject.physicsBody?.categoryBitMask = PhysicsCategoryBitmask.Platform
bottomObject.physicsBody?.affectedByGravity = true
bottomObject.physicsBody?.friction = 0.0
//bottomObject.physicsBody?.restitution = 1.0
bottomObject.physicsBody?.linearDamping = 0.0
bottomObject.physicsBody?.angularDamping = 0.0
bottomObject.physicsBody?.mass = 500.0
node.addChild(bottomObject)
let jointLast = SKPhysicsJointFixed.jointWithBodyA(lastLinkItem!.physicsBody!, bodyB: bottomObject.physicsBody!, anchor: CGPointMake(position.x, position.y + bottomObject.position.y + bottomObject.frame.size.height/2.0))
jointArray.append(jointLast)
///////
///////
sprite = SKSpriteNode(imageNamed: imageName)
//sprite.setScale(SceneObjectSizeScale.ActionSceneObject)
node.sprite = sprite
//node.addChild(sprite)
node.physicsBody = SKPhysicsBody(texture: texture, size: sprite.size)
node.physicsBody!.categoryBitMask = PhysicsCategoryBitmask.None
switch actionDirection {
case .Left:
node.sprite.zRotation = CGFloat(M_PI_2)
case .Right:
node.sprite.zRotation = CGFloat(-M_PI_2)
case .Down:
node.sprite.zRotation = CGFloat(M_PI)
case .Up, .Unknown:
break
}
node.physicsBody?.dynamic = true
node.physicsBody?.restitution = 0.0 // bounciness
node.physicsBody?.categoryBitMask = PhysicsCategoryBitmask.ActionSceneObject
node.physicsBody?.collisionBitMask = 0
return (node, jointArray)
}
I´m making a little game were I have a matrix compose for SKSpriteNode and numbers, when the game its over I´m trying to make an animation were I go over the matrix changing only the sprite one by one following the order of the numbers. Look the
Board (The squares are in a Sknode and the number in other Sknode)
The Idea is change the sprite to other color and wait 2 sec after change the next but I can´t do it. I don't know how to change the sprite one by one. I make this function "RecoverMatrix()", this change the sprites but all at once, it is as if not take the wait, he change all the sprites and before wait the 2 sec.
func RecoverMatrix() {
var cont = 1
TileLayer.removeAllChildren()
numLayer.removeAllChildren()
let imageEnd = SKAction.setTexture(SKTexture(imageNamed: "rectangle-play"))
let waiting = SKAction.waitForDuration(2)
var scene: [SKAction] = []
var tiles: [SKSpriteNode] = []
while cont <= 16 {
for var column = 0; column < 4; column++ {
for var row = 0; row < 4; row++ {
if matrix[column][row].number == cont {
let label = SKLabelNode()
label.text = "\(matrix[column][row])"
label.fontSize = TileHeight - 10
label.position = pointForBoard(column, row: row)
label.fontColor = UIColor.whiteColor()
let tile = SKSpriteNode()
tile.size = CGSize(width: TileWidth - 3, height: TileHeight - 3)
tile.position = pointForBoard(column, row: row, _a: 0)
TileLayer.addChild(tile)
numLayer.addChild(label)
tiles.append(tile)
scene.append(SKAction.sequence([imageEnd, waiting]))
tile.runAction(imageEnd)
runAction(waiting)
didEvaluateActions()
}
}
}
cont++
}
for tile in tiles {
tile.runAction(SKAction.sequence(scene))
self.runAction(SKAction.waitForDuration(1))
}
}
So, I need help, I don't find the way to make this animation. I really appreciate the help. Thanks!
This is how you can run an action on every node at the same time (using a loop to loop through all the tiles):
class GameScene: BaseScene, SKPhysicsContactDelegate {
var blocks: [[SKSpriteNode]] = []
override func didMoveToView(view: SKView) {
makeBoard(4, height: 4)
colorize()
}
func makeBoard(width:Int, height:Int) {
let distance:CGFloat = 50.0
var blockID = 1
//make a width x height matrix of SKSpriteNodes
for j in 0..<height {
var row = [SKSpriteNode]()
for i in 0..<width {
let node = SKSpriteNode(color: .purpleColor(), size: CGSize(width: 30, height: 30))
node.name = "\(blockID++)"
if let nodeName = node.name {node.addChild(getLabel(withText: nodeName))}
else {
//handle error
}
node.position = CGPoint(x: frame.midX + CGFloat(i) * distance,
y: frame.midY - CGFloat(j) * distance )
row.append(node)
addChild(node)
}
blocks.append(row)
}
}
func colorize() {
let colorize = SKAction.colorizeWithColor(.blackColor(), colorBlendFactor: 0, duration: 0.5)
var counter = 0.0
let duration = colorize.duration
for row in blocks {
for sprite in row {
counter++
let duration = counter * duration
let wait = SKAction.waitForDuration(duration)
sprite.runAction(SKAction.sequence([wait, colorize]))
}
}
}
func getLabel(withText text:String) -> SKLabelNode {
let label = SKLabelNode(fontNamed: "ArialMT")
label.fontColor = .whiteColor()
label.text = text
label.fontSize = 20
label.horizontalAlignmentMode = .Center
label.verticalAlignmentMode = .Center
return label
}
}
And the result:
So basically, as I said in the comments, you can run all the actions at the same moment, it is just about when the each action will start.
You seem to imagine that runAction(waiting) means that you code pauses and waits, pausing between loops. It doesn't (and in fact there is no way to do that). Your code loops through all the loops, now, KABOOM, immediately.
Thus, all the actions are configured immediately and are performed together.