用随机坐标重复UIAnimation

时间:2016-09-01 15:28:58

标签: ios swift xcode animation uiview

我试图创建一个动画,在给定的延迟时间内将屏幕上的圆圈移动到随机点。

我的问题是,当我打电话重复动画时。它将我的圆圈移回原点并使用完全相同的坐标重复精确的动画。有没有办法让我有一个重复动画,每次都会调用新的坐标?

startAnimations():

store.sort({
    property:'name',
    direction:'ASC'
})

moveCircle():

func startAnimations() {

    UIView.beginAnimations(nil, context: nil)
    UIView.setAnimationDelay(gameSpeed)
    UIView.setAnimationRepeatCount(100)

    moveCircle()

    UIView.setAnimationDelegate(self)
    UIView.setAnimationDidStopSelector(#selector(killFloor))

    UIView.commitAnimations()
}

grabRandomPoint():

func moveCircle() {
    self.view.layoutIfNeeded()

    animator.removeAllBehaviors()

    let randomPoint = grabRandomPoint(from: self)
    print("Random Point (\(randomPoint.x), \(randomPoint.y))")
    circle.center = randomPoint
}

1 个答案:

答案 0 :(得分:1)

您好我一直在处理您的问题,这是我发现的,检查此代码,此代码永远不会停止,但您可以使用执行次数定义变量

    func startAnimations() {

        UIView.beginAnimations(nil, context: nil)
        UIView.setAnimationDelay(0.5)
        moveCircle()

        UIView.setAnimationDelegate(self)
        UIView.setAnimationDidStopSelector(#selector(self.startAnimations))
        UIView.commitAnimations()
    }

    func moveCircle() {
        self.view.layoutIfNeeded()

        //animator.removeAllBehaviors()

        let randomPoint = grabRandomPoint(from: self)
        print("Random Point (\(randomPoint.x), \(randomPoint.y))")
        objectToMove.center = randomPoint
    }

    func grabRandomPoint(from vc: ViewController) -> CGPoint {
        // x coordinate between MinX (left) and MaxX (right):
        let randomX = randomIntBewtween(Int(CGRectGetMinX(vc.view.frame)), max: Int(CGRectGetMaxX(vc.view.frame)))
        // y coordinate between MinY (top) and MidY (middle):
        let randomY = randomIntBewtween(Int(CGRectGetMinY(vc.view.frame)), max: Int(CGRectGetMidY(vc.view.frame)))
        let randomPoint = CGPoint(x: randomX, y: randomY)

        return randomPoint
    }

这是我在

之间找到Random值的代码
func randomIntBewtween(min : Int, max : Int) ->Int
{
    let randomNumber = arc4random_uniform(UInt32(max) - UInt32(min)) + UInt32(min)
    return Int(randomNumber)
}

我希望这有助于你