简体   繁体   中英

Stop a movement in SpriteKit swift4 Xcode and set a timer to switch Players

how can I stop dynamic balls that I create to but them in goals but I should stop them after moving for a little bit so I can switch the Player to another one if its not a goal , the Balls keep moving while Im switching the Players ? help please!

are you working on a football game or something like that? If so, you could write your code in Update() func of SKScene. I think it is no need to set a timer. For example, if it is a football game, you can build a ball with SKPhysicsBody, like this in the GameScene class inherited from SKScene

let ballNode = SKSpriteNode(imageNamed: "ball.png")
var players: [SKSpriteNode]!

func buildBall() {
    addChild(ballNode)
    ballNode.name = "Ball"

    ballNode.physicsBody = SKPhysicsBody(texture: ballNode.texture!, size: ballNode.size)
    ballNode.physicsBody?.affectedByGravity = false
}

then you can move the ball using its property named velocity(), like this:

func moveBall(velocity: CGVector) {
     ballNode.physicsBody?.velocity = velocity
}

then build the players:

func buildPlayers() {
     for i in 0...10 {
          let playerNode = SKSpriteNode(fileNamed: "player.png")
          addChild(playerNode)
          players.append(playerNode)
          playerNode.physicsBody = SKPhysicsBody(texture: playerNode.texture!, size: playerNode.size)
          playerNode.physicsBody?.affectedByGravity = false
     }
}

Then you can write the code in update() method:

override func update(_ currentTime: TimeInterval) {
    var nearestPlayer: SKSpriteNode!
    var distance = 9999999
    for player in players {
         let temp = sqrt((player.position.x - ballNode.position.x) * (player.position.x - ballNode.position.x) + (player.position.y - ballNode.position.y) * (player.position.y - ballNode.position.y))// calculate the distance
         if temp < distance {
             nearestPlayer = player //Get the nearestPlayer
             distance = temp
         }
    }

    switchPlayer(player: nearestPlayer)//This is a switchPlayer method which I didn't defined
 }

to stop the ball, just set the ball's velocity to CGVector(dx: 0, dy: 0).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM