[英]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 ? 如何停止我创建的动态球,但将其锁定在目标中,但是在移动了一点之后就应该停止它们,以便我可以将播放器切换到另一个(如果不是目标),则球会继续移动,而Im会切换玩家? 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.
如果是这样,您可以在SKScene的Update()函数中编写代码。 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
例如,如果是足球比赛,则可以使用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
}
then you can move the ball using its property named velocity(), like this: 那么您可以使用其名为Velocity()的属性来移动球,如下所示:
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: 然后,您可以在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
}
to stop the ball, just set the ball's velocity to CGVector(dx: 0, dy: 0). 要停止球,只需将球的速度设置为CGVector(dx:0,dy:0)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.