Search code examples
iosswiftuiviewuianimation

Move view in direction of specific angle


I have an angle that I am calculating based on the positioning of a view from the centre of the screen. I need a way to move the view from it's current position, off the screen in the direction of the angle.

I'm sure there is a fairly simple way of calculating a new x and y value, but I haven't been able to figure out the maths. I want to do it using an animation, but I can figure that out myself once I have the coordinates.

Anyone have any suggestions?


Solution

  • If you have angle you can calculate new coordinates by getting sine and cosine values. You can try out following code

    let pathLength = 50 as Double // total distance view should move
    let piFactor = M_PI / 180
    let angle = 90 as Double // direction in which you need to move it
    let xCoord = outView.frame.origin.x +  CGFloat(pathLength * sin(piFactor*angle)) //outView is name of view you want to animate
    let yCoord = outView.frame.origin.y +  CGFloat(pathLength * cos(piFactor*angle))
    UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
        self.outView.frame = CGRectMake(xCoord, yCoord, self.outView.frame.size.width, self.outView.frame.size.height)
            }, completion: { (Bool) -> Void in
    })