Search code examples
iosswiftuiimageprojectile

making a UIimage move every 1 second


I have a UIimage which I want to move according to X and Y given by certain equations ( physics projectile time equations) and I want it to move every 1 second so that it would appear to the user as if it's actually moving not just disappearing and reappearing at the last position, plus the positions given off are wrong I think. I would appreciate any help for either or both problems.

So far I tried this:

The movement function:

func moveCannonBall(toX:Int , toY:Int ){
    var frm: CGRect = ballimageview.frame
    frm.origin.x = frm.origin.x + CGFloat(toX)
    frm.origin.y = frm.origin.y - CGFloat(toY)
    ballimageview.frame = frm
}

On button click it's supposed to take the user's inputs (gravity, angle, and the initial speed)

@IBAction func getAlpha( sender:AnyObject){
    gravity = Float(g[pickerView.selectedRow(inComponent: 0)])
    xMax = ((V0*V0)*sin(2.0*angle))/gravity

It's supposed to stop every 1 second but only the calculations pause every 1 second and the UIimage just disappears and reappears just

    while Int(toX) < Int(xMax)  {
        sleep(1)
        t = t + 1

        toX = V0*cos(angle)*t
        toY = -0.5*gravity*t*t + V0*sin(angle)*t

        moveCannonBall(toX: Int(toX), toY: Int(toY))
    }
}

Any help is appreciated.


Solution

  • As Losiowaty said UIView.animationWithDuration is the way to go. Check out this answer to see how the syntax is: https://stackoverflow.com/a/30992214/5257729