Search code examples
iosswiftuiimageview

How to move a UIImageView towards a certain point based on its degrees rotation?


I have a rocket UIImageView that constantly rotates around itself with an NSTimer:

 rotationDegrees = rotationDegrees + 0.5
 rocket.transform = CGAffineTransformMakeRotation(rotationDegrees * CGFloat(M_PI/180) )

Once I tap on the screen, I need it to simply fire it into a specific trajectory (I'm using UIKit, no SpriteKit, so please no SpriteKit suggestions :) Here's a picture as an example of trajectory:

enter image description here

My touchesBegan() method:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    // Invalidate the timer that rotates the Rocket
        rotationTimer.invalidate()
    
        // Fire timer that moves the Rocket
        moveRocketTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "moveRocket", userInfo: nil, repeats: true)
}

Here's the function where I need to move the Rocket like 8 points X and 8 points Y

func moveRocket() {
  rocket.center.x = ??? + 8
  rocket.center.y = ??? + 8
}

I'm using a NSTimer to move the rocket because I need to check its collision with another view by using if CGRectIntersectsRect().


Solution

  • You need to use trigonometry to calculate the change in x & y for a given angle:

    y = sin(angle);
    x = cos(angle);
    

    That will give you values that range from -1 to 1. You'll need to scale them as desired (In your question you multiply by 8.

    Your angle values need to be in radians. So if your angle is in degrees, you might want to write a function to convert degrees to radians:

    func radiansFromDegrees(degrees: Float) -> Float
    {
      return degrees * M_PI/180;
    }
    

    And if you want your ship to move 8 points / frame then you should multiply by 8. So that would give you:

    rocket.center.y += 8.0 * sin(radiansFromDegrees(angle));
    rocket.center.x += 8.0 * cos(radiansFromDegrees(angle));
    

    You'll probably have to do some type-casting to make the compiler happy, since I think sin and cos return doubles.