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

在这里我打电话给带有计时器的形状功能

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


在这里我做一个随机的位置动作并永久重复该动作,但是每个形状只运行一次

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

最佳答案

每个函数仅每个精灵调用一次。

您要执行的操作如下:


得到一个随机的x,y位置---假设它得到了120,200
移至120,200 ---并重复永久移至120,200


因此,精灵将忠实地移动到该随机位置,并继续移动到该位置。它永远不会回到起点,也永远不会获得新的位置。

如果希望精灵继续移动到新的随机位置,则每次当前移动完成时都需要创建一个新的随机位置。

10-07 19:41
查看更多