簡體   English   中英

停止SpriteKit swift4 Xcode中的移動並設置計時器以切換播放器

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

如何停止我創建的動態球,但將其鎖定在目標中,但是在移動了一點之后就應該停止它們,以便我可以將播放器切換到另一個(如果不是目標),則球會繼續移動,而Im會切換玩家? 請幫助!

您是在進行足球比賽還是類似的工作? 如果是這樣,您可以在SKScene的Update()函數中編寫代碼。 我認為沒有必要設置計時器。 例如,如果是足球比賽,則可以使用SKPhysicsBody構造一個球,就像在繼承自SKScene的GameScene類中那樣

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
}

那么您可以使用其名為Velocity()的屬性來移動球,如下所示:

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

然后建立玩家:

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
     }
}

然后,您可以在update()方法中編寫代碼:

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
 }

要停止球,只需將球的速度設置為CGVector(dx:0,dy:0)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM