2

I am using swift spritekit.

Hi, I have a couple of questions about M_PI, which I recently learnt about. For my game, I have been researching different ways to rotate things. Basically, in my game there are 2 planes "flying" around the center of the screen.

NOTE: When I tried to use M_PI Xcode warned me to use double.pi, which I used to replace M_PI. Are these things the same thing?

  1. I tried to work out how to rotate a plane around the centre of the screen. I found out that the best way to do that was to make that a child to a centre node and then rotate the centre node, using this line of code:

        let OrbitCenter = SKAction.rotate(byAngle: CGFloat(-2 * Double.pi), duration: 3.8)
    

    When I took away the Double.pi, the planes moved a lot slower but still rotated in the same way. Why do we need to use Double.pi?

  2. I wanted one of the planes/SKSpriteNodes to be upside down, so I researched and found this: PlaneBlue.zRotation = CGFloat(16.0). Again, when I take away the Double.pi, it has the same effect however it is just pointing somewhere else.

Overall, my two questions are, is Double.pi the same as M_PI, but just Double.pi is the new way of using this or are they different. Also, why do we need to use Double.pi/M_PI?

Thank you in advance.

Lucas Smith
  • 698
  • 2
  • 9
  • 17

1 Answers1

3

Double.pi is used in this sample because rotate(byAngle:duration:) takes an angle in radians. 2π radians is equal to one full rotation, or 360 degrees. The code you included is creating a rotation action telling the plane to rotate one full rotation every 3.8 seconds. Removing the Double.pi is just causing it to rotate a smaller angle every 3.8 seconds.

As for the difference between M_PI and Double.pi, they're basically the same. The latter is newer and matches similar constants on other types, such as CGFloat.pi. These other constants allow you to get correctly-typed values of π for other numeric types. M_PI was always a Double, but CGFloat.pi is a CGFloat, Float.pi is a Float, etc.

In fact, in your code, switching to CGFloat.pi might allow you to remove the CGFloat cast around your angle parameter, like so:

let OrbitCenter = SKAction.rotate(byAngle: -2 * CGFloat.pi, duration: 3.8)

Cocoatype
  • 2,572
  • 25
  • 42
  • 1
    Swift is a type inferred language. no need to specify the `.pi` type `let orbitCenter = SKAction.rotate(byAngle: -2 *.pi, duration: 3.8)` – Leo Dabus Apr 10 '17 at 05:13
  • BTW it Swift is convention to name your vars starting with a lowercase letter – Leo Dabus Apr 10 '17 at 05:14
  • Unless you're using something without inference. Then you'll get a `ambiguous use of 'pi'` error. Sometimes you need `CGFloat.pi` etc. – Edison Aug 19 '17 at 05:35