在屏幕上以随机位置永远移动精灵

Move sprite forever with random postion on screen

我试图随机移动我的精灵(正方形),但所有精灵都去到相同的位置和 ״vibrating״。 永远移动精灵并随机位置的最佳方法是什么?

//Make random shape
func makeShape () {

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

        sprite = shape.copy() as! SKShapeNode
        sprite.name = "Shpae \(shapesamount)"

        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(move)
}

override func update(_ currentTime: TimeInterval) {

    // Called before each frame is rendered
    if istouching && !isOver {
        let dt:CGFloat = 1.0/50.0
        let distance = CGVector(dx: touchpoint.x - circle.position.x, dy: touchpoint.y - circle.position.y)
        let velocity = CGVector(dx: distance.dx/dt, dy: distance.dy/dt)
        self.circle.physicsBody!.velocity = velocity
    }

    if isOver == false {
        for nodee in shapes.children {
            moveRandom(node: nodee as! SKShapeNode)
        }
    }
}

}

shapes 是 SKNode

您不断地向您的节点添加移动动作,这就是它振动的原因。你实际上是在让它们每一帧都向各个方向移动。

相反,添加检查以查看是否有任何操作是 运行,如果不是,则更改位置:

  if isOver == false {
        for nodee in shapes.children {
            guard !nodee.hasActions else {continue}
            moveRandom(node: nodee as! SKShapeNode)
        }
    }