msqar - 1 year ago 62

iOS Question

I would like to do some calculations based on an angle, but I can't find a way to find a replacement of ccpForAngle() from Cocos2D to SpriteKit. It basically gives a x,y CGPoint based on a passed angle value.

Answer Source

`ccpForAngle()`

is defined in the cocos2d framework as

```
/** Converts radians to a normalized vector.
@return CGPoint
*/
static inline CGPoint
ccpForAngle(const CGFloat a)
{
return ccp((CGFloat)cos(a), (CGFloat)sin(a));
}
```

where `ccp()`

is

```
/** Helper macro that creates a CGPoint
@return CGPoint
*/
static inline CGPoint ccp( CGFloat x, CGFloat y )
{
return CGPointMake(x, y);
}
```

That can be directly translated to Swift:

```
func CGPointForAngle(angle: CGFloat) -> CGPoint {
return CGPoint(x: cos(angle), y: sin(angle))
}
```

but the more Swifty way is to define an initializer:

```
extension CGPoint {
init(angle: CGFloat) {
self.init(x: cos(angle), y: sin(angle))
}
}
```

which can then be used as

```
let pt = CGPoint(angle: CGFloat(M_PI)/3.0)
print(pt) // (0.5, 0.866025)
```

to create a point on the unit circle at 60 degrees from the positive x-axis.