停止SpriteKit swift4 Xcode中的移动,并设置计时器切换播放器
我怎样才能阻止我创造的动态球,但它们是在进球时,但我应该在移动一点后停止它们,这样我就可以将球员切换到另一个球员。如果不是进球,球会在我切换球员时继续移动?停止SpriteKit swift4 Xcode中的移动,并设置计时器切换播放器,swift,xcode,dynamic,sprite-kit,Swift,Xcode,Dynamic,Sprite Kit,我怎样才能阻止我创造的动态球,但它们是在进球时,但我应该在移动一点后停止它们,这样我就可以将球员切换到另一个球员。如果不是进球,球会在我切换球员时继续移动? 救命啊 你是在做足球比赛之类的事吗?如果是这样,您可以在SKScene的Update()func中编写代码。我认为没有必要设置计时器。例如,如果是一场足球比赛,可以使用SKPhysicsBody构建一个球,就像从SKScene继承的GameSecene类中这样 let ballNode = SKSpriteNode(imageNamed:
救命啊 你是在做足球比赛之类的事吗?如果是这样,您可以在SKScene的Update()func中编写代码。我认为没有必要设置计时器。例如,如果是一场足球比赛,可以使用SKPhysicsBody构建一个球,就像从SKScene继承的GameSecene类中这样
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()方法中编写代码:
覆盖函数更新(\uCurrentTime:TimeInterval){
最近的玩家:斯普林泰诺德!
变量距离=9999999
球员中的球员{
让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))//计算距离
如果温度<距离{
nearestPlayer=玩家//获取最接近的玩家
距离=温度
}
}
switchPlayer(player:nearestPlayer)//这是一个我没有定义的switchPlayer方法
}
要停止球,只需将球的速度设置为CGVector(dx:0,dy:0)。嗨,Mariam,你能给我解释一下你的问题吗。据我所知,这似乎是一个多线程的问题。使用计时器时,请确保只在主线程中调用计时器。
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
}