Ios 精灵在随机位置移动一次

Ios 精灵在随机位置移动一次,ios,random,sprite-kit,action,Ios,Random,Sprite Kit,Action,我试图移动精灵在屏幕上随机移动,但精灵一次移动到随机位置并停止移动 在这里,我用定时器调用makeshapefunc //Make shape Timer func makeshapetimer () { maketimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(makerandomShape), userInfo: nil, repeats: true) } //

我试图移动精灵在屏幕上随机移动,但精灵一次移动到随机位置并停止移动

在这里,我用定时器调用makeshapefunc

    //Make shape Timer
func makeshapetimer () {
    maketimer = Timer.scheduledTimer(timeInterval: 3.0, target: self, selector: #selector(makerandomShape), userInfo: nil, repeats: true)
}

//Make random shape
func makerandomShape () {

    //Check if have more than 12 shapes
    if shapesamount <= 12 {

        let sprite = shape.copy() as! SKShapeNode
        sprite.name = "Shpae \(shapesamount)"
        sprite.position = CGPoint(x: frame.minX - sprite.frame.width, y: frame.maxY)

        shapes.addChild(sprite)

        shapesamount += 1

        moveRandom(node: sprite)
    }
}

您的
moveRandom
函数每个精灵只调用一次

以下是您告诉它要做的:

  • 得到一个随机的x,y位置——假设它得到120200
  • 移动到120200---并永远重复移动到120200
因此,精灵尽职尽责地移动到那个随机位置,并一直移动到那个位置。它永远不会回到起点,也永远不会有新的位置去移动


如果你想让精灵继续移动到新的随机位置,你需要在每次移动结束时创建一个新的随机位置。

不要在精灵套件中使用
计时器
,而是使用SKAction。计时器不会附着在精灵套件游戏循环中,WIN;如果场景暂停,请不要停止etcSKAction.wait而不是计时器
//Move shape radmonly
func moveRandom (node: SKShapeNode) {

    move = SKAction.move(to: CGPoint(x: CGFloat.random(min: frame.minX, max: frame.maxX), y: CGFloat.random(min: frame.minY, max: frame.maxY)), duration: shapespeed)

    node.run(SKAction.repeatForever(move))
}