0

I have a UIImageView which moves across the screen, but I would like the image to rotate so the top of the image is facing the direction of motion.

func shootStar(backgroundImage: UIImageView){
    let screenSize = UIScreen.main.bounds
    let screenHeight = screenSize.height
    let screenWidth = screenSize.width
    let star = UIImage(named: "Shooting Star")
    let starView = UIImageView(image: star!)

    starView.frame = CGRect(x: -40,y: screenHeight*0.05, width: 38.5, height: 42.8)
    view.insertSubview(starView, aboveSubview: backgroundImage)

    let toPoint:CGPoint = CGPoint(x: screenWidth + 80, y: screenHeight*0.3)
    let fromPoint:CGPoint = CGPoint(x: -40, y: 40)
    let movement = CABasicAnimation(keyPath: "position")
    movement.isAdditive = true
    movement.fromValue = NSValue(cgPoint: fromPoint)
    movement.toValue = NSValue(cgPoint: toPoint)
    movement.duration = 5
    starView.layer.add(movement, forKey: "move")
}
  • Possible duplicate of [Rotate an object in its direction of motion](https://stackoverflow.com/questions/31421912/rotate-an-object-in-its-direction-of-motion) – mugx Nov 21 '17 at 11:35
  • This is about UIImageViews not sprites –  Nov 21 '17 at 11:40
  • It is irrelevant. What you need is the rotation angle (zRotation) – mugx Nov 21 '17 at 11:41

1 Answers1

0

Your difficulty here probably has to do with the fact that iOS does not use cartesian coordiantes but the atan2 function does. Here is an example playground of how to calculate the angle and use the transform to align the imageview in the direction of travel. I'm using UIView transforms and animations here, but the same principles and coordinate system applies to CALayer's and CAAnimations:

import PlaygroundSupport
import UIKit

class V: UIViewController {
    let imageView = UIImageView()
    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.image = UIImage(named: "arrow up.jpg")
        view.addSubview(imageView)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        imageView.sizeToFit()
        imageView.center = view.center
        let vector = CGVector(dx: 120, dy: 100)
        let angle = atan2(vector.dy, vector.dx) - 1.5 * CGFloat.pi
        print(angle/CGFloat.pi)
        let rotationMatrix = CGAffineTransform(rotationAngle: angle)
        self.imageView.transform = rotationMatrix
        UIView.animate(withDuration: 5) {
            self.imageView.center.x += vector.dx
            self.imageView.center.y += vector.dy
        }

    }
}

PlaygroundPage.current.liveView = V()
Josh Homann
  • 15,933
  • 3
  • 30
  • 33