In Swift, I have two related properties of a structure that I want to keep in sync.
I'm currently doing this with property observers but I've had to add an extra flag to prevent them playing an infinite game of ping-pong with each other.
Is there a more elegant and/or transparent way to achieve this?
A simplified example:
import Foundation
struct Angle {
var blockPropertyObservers = false
var degrees: Double {
willSet(degrees) {
print("will set degrees to \(degrees)")
if !blockPropertyObservers {
blockPropertyObservers = true
radians = (degrees / 360) * 2 * M_PI
} else {
blockPropertyObservers = false
}
}
}
var radians: Double {
willSet(radians) {
print("will set radians to \(radians)")
if !blockPropertyObservers {
blockPropertyObservers = true
degrees = (radians / (2 * M_PI)) * 360
} else {
blockPropertyObservers = false
}
}
}
init(inDegrees degrees: Double) {
self.degrees = degrees
self.radians = (degrees / 360) * 2 * M_PI
}
init(inRadians radians: Double) {
self.radians = radians
self.degrees = (radians / (2 * M_PI)) * 360
}
}
Ideally, I'd also like to find a way to avoid having to replicate the code for the conversions in the init() routines...
You could use a computed property for one of those two, let's say for degrees. This will reduce the boiler plate code, without losing functionality for your struct.
struct Angle {
var degrees: Double {
get { return radians / (2 * M_PI) * 360 }
set { radians = (newValue / 360) * 2 * M_PI}
}
var radians: Double = 0.0
init(inDegrees degrees: Double) {
self.degrees = degrees
}
init(inRadians radians: Double) {
self.radians = radians
}
}
Related
I'm trying to get a UIView called object to rotate to point at the center of another UIView called orig. I can't seem to be able to calculate the angle correctly. My trig is a bit rusty so I can't figure out how my math is wrong.
let y0 = object.center.y
let y1 = orig?.center.y
let x0 = object.center.x
let x1 = orig?.center.x
let angle = atan2((y1! - y0), (x1! - x0)) * 180 / CGFloat.pi
rotateTo(object: object, degrees: angle, time: deplexed[1] as! CGFloat)
To make the top of rotator view point at the target point.
let direction = CGPoint(x: targetPoint.x - rotatorView.center.x, y: targetPoint.y - rotatorView.center.y)
var angle = atan2(direction.y, direction.x)
rotatorView.transform = CGAffineTransform(rotationAngle: angle + .pi/2)
atan2 returns zero if point is to the right.
If you want to convert the atan2 result to degrees:
if angle < 0 {
angle += .pi * 2
}
let degrees = angle * 180.0/.pi
You add a full circle if the angle is negative. 0 degrees points to the right.
Create a default object and suppose it's a button :
let button = UIButton()
if button.transform == CGAffineTransform.identity {
UIView.animate(withDuration: 0.5, animations: {
button.transform = CGAffineTransform(rotationAngle: self.radians(degrees: 180))
})
} else {
UIView.animate(withDuration: 0.5, animations: {
button.transform = CGAffineTransform.identity
})
}
func radians(degrees: CGFloat) -> CGFloat {
return CGFloat(degrees * CGFloat.pi / degrees)
}
I have player (SKSpriteNode) he can move and rotate, and I want to shoot five bullets from him, but with another angle. I use this code:
let sinus = sin(player.zRotation)
let cosinus = cos(player.zRotation)
bullet.physicsBody!.applyImpulse(CGVector(dx: -sinus * 100, dy: cosinus * 100))
But, i do not know how to correctly set the vector with angle. I try to make something like this:
Can anyone help me please!
According with this diagram:
you must change the zRotation of your bullets.
Remember that zRotation is expressed in radians so if you need:
extension CGFloat {
var radiansToDegrees: CGFloat {
return self * CGFloat(180.0 / M_PI)
}
var degreesToRadians: CGFloat {
return self * CGFloat(M_PI / 180.0)
}
}
To rotate your bullets you can also use (also this one is expressed in radians) :
let rotate = SKAction.rotateByAngle(angle, duration: 0.01)
You can calculate also the speed and the angle of your bullet impulses :
extension CGVector {
func speed() -> CGFloat {
return sqrt(dx*dx+dy*dy)
}
func angle() -> CGFloat {
return atan2(dy, dx)
}
}
If you need you can connect these element with the screen touches as explained in detail here
About your comments you can use this formula (already explained in my link):
let angle = atan2(location.y - cannon.position.y , location.x - cannon.position.x)
cannon.zRotation = angle - CGFloat(M_PI_2)
I've been playing with Swift and I encoded an obvious conversion structure:
struct MutableAngle {
var degrees : CGFloat
var radians : CGFloat {
return degrees * CGFloat(M_PI) / 180.0
}
init(inRadians : CGFloat) {
degrees = inRadians * 180.0 / CGFloat(M_PI)
}
init(inDegrees : CGFloat) {
degrees = inDegrees
}
}
Now this is fine but inelegant since it doesn't treat degrees and radians symmetrically although it does give mutability. This is really a structure which should be called Degrees and which can provide radians. For instance, I can write:
var angle : MutableAngle
angle.degrees = 45.0
but not
var angle : MutableAngle
angle.radians = 0.75
Here's a final version:
struct Angle {
let degrees : CGFloat
let radians : CGFloat
init(inRadians : CGFloat ) {
radians = inRadians
degrees = radians * CGFloat (180 / M_PI)
}
init(inDegrees : Float ) {
degrees = inDegrees
radians = degrees * CGFloat (M_PI / 180)
}
}
Use as follows:
var alpha = Angle(inDegrees: 45)
alpha.degrees // returns 45
alpha.radians // returns 0.7853982
// alpha.radians = 0.9 ... is now illegal with let constants
// must use constructor ... provided alpha was defined using 'var'
// i.e. the struct itself is mutable
alpha = Angle(inRadians: 0.9)
alpha.radians // returns 0.7853982
alpha.degrees // returns 45
Switching from var to let makes it mutable/immutable depending on how alpha is defined and I'm now obliged to use the constructors which is good. So its symmetric. It also has the merit that a calculation is not required every time I want to use the radians.
Two things here:
In Swift you don't need a separate mutable type for value types - that's handled by whoever is instantiating the type by using let or var.
Your radians computed property only has a getter - you can do what you want with both a setter and a getter.
My implementation:
struct Angle {
var degrees : CGFloat = 0
var radians : CGFloat {
get {
return degrees * CGFloat(M_PI) / 180.0
}
set {
degrees = newValue * 180.0 / CGFloat(M_PI)
}
}
init(inRadians : CGFloat) {
radians = inRadians
}
init(inDegrees : CGFloat) {
degrees = inDegrees
}
}
Useage:
// immutable
let angle = Angle(inDegrees: 180)
println(angle.radians)
// next line gives an error: can't assign to an immutable instance
angle.radians = angle.radians * 2
// mutable copy
var mutableAngle = angle
mutableAngle.degrees = 10
println(mutableAngle.radians)
// 0.1745...
mutableAngle.radians = CGFloat(M_PI)
println(mutableAngle.degrees)
// 180.0
A possible solution is to use enum with associated value:
enum MutableAngle {
case Radian(CGFloat)
case Degree(CGFloat)
init(radians:CGFloat) {
self = .Radian(radians)
}
init(degrees:CGFloat) {
self = .Degree(degrees)
}
var radians:CGFloat {
get {
switch self {
case .Radian(let val): return val
case .Degree(let val): return val * CGFloat(M_PI) / 180.0
}
}
set {
self = .Radian(newValue)
}
}
var degrees:CGFloat {
get {
switch self {
case .Degree(let val): return val
case .Radian(let val): return val * 180.0 / CGFloat(M_PI)
}
}
set {
self = .Degree(newValue)
}
}
}
var angle = MutableAngle(radians: 1)
angle.degrees // -> 57.2957795130823
angle.degrees = 180
angle.radians // -> 3.14159265358979
Does anyone have a calculation that calculates the new
latitude and longitude based on a starting point, bearing and
distance?
I would greatly appreciate any help people might have.
I've used the code from Calculate new coordinate x meters and y degree away from one coordinate:
- (CLLocationCoordinate2D)coordinateFromCoord:(CLLocationCoordinate2D)fromCoord
atDistanceKm:(double)distanceKm
atBearingDegrees:(double)bearingDegrees
{
double distanceRadians = distanceKm / 6371.0;
//6,371 = Earth's radius in km
double bearingRadians = [self radiansFromDegrees:bearingDegrees];
double fromLatRadians = [self radiansFromDegrees:fromCoord.latitude];
double fromLonRadians = [self radiansFromDegrees:fromCoord.longitude];
double toLatRadians = asin(sin(fromLatRadians) * cos(distanceRadians)
+ cos(fromLatRadians) * sin(distanceRadians) * cos(bearingRadians) );
double toLonRadians = fromLonRadians + atan2(sin(bearingRadians)
* sin(distanceRadians) * cos(fromLatRadians), cos(distanceRadians)
- sin(fromLatRadians) * sin(toLatRadians));
// adjust toLonRadians to be in the range -180 to +180...
toLonRadians = fmod((toLonRadians + 3*M_PI), (2*M_PI)) - M_PI;
CLLocationCoordinate2D result;
result.latitude = [self degreesFromRadians:toLatRadians];
result.longitude = [self degreesFromRadians:toLonRadians];
return result;
}
- (double)radiansFromDegrees:(double)degrees
{
return degrees * (M_PI/180.0);
}
- (double)degreesFromRadians:(double)radians
{
return radians * (180.0/M_PI);
}
Or in Swift:
extension CLLocationCoordinate2D {
func adjusted(distance: Double, degrees: Double) -> CLLocationCoordinate2D {
let distanceRadians = distance / 6_371 // 6,371 == Earth's radius in km
let bearingRadians = degrees.radians
let fromLatRadians = latitude.radians
let fromLonRadians = longitude.radians
let toLatRadians = asin(sin(fromLatRadians) * cos(distanceRadians) + cos(fromLatRadians) * sin(distanceRadians) * cos(bearingRadians))
var toLonRadians = fromLonRadians + atan2(sin(bearingRadians)
* sin(distanceRadians) * cos(fromLatRadians), cos(distanceRadians)
- sin(fromLatRadians) * sin(toLatRadians))
// adjust toLonRadians to be in the range -180 to +180...
toLonRadians = fmod((toLonRadians + 3 * .pi), (2 * .pi)) - .pi
return CLLocationCoordinate2D(latitude: toLatRadians.degrees, longitude: toLonRadians.degrees)
}
}
extension CLLocationDegrees {
var radians: Double { self * .pi / 180 }
}
extension Double {
var degrees: CLLocationDegrees { self * 180 / .pi }
}
You will find all the calculations you could possibly want (including explanations etc) at http://www.movable-type.co.uk/scripts/latlong.html
The code you need is (in JavaScript) under the heading "Destination point given distance and bearing from start point". Excerpting:
var lat2 = Math.asin( Math.sin(lat1)*Math.cos(d/R) +
Math.cos(lat1)*Math.sin(d/R)*Math.cos(brng) );
var lon2 = lon1 + Math.atan2(Math.sin(brng)*Math.sin(d/R)*Math.cos(lat1),
Math.cos(d/R)-Math.sin(lat1)*Math.sin(lat2));
Where R = radius of the earth, d = distance (in same units), and lat/long are in radians (since that's what the sin function expects). You go from degrees to radians with
radians = pi * degrees / 180;
You should be able to take it from here. Do look at the link I gave for more info.
I'm trying to write a category for CLLocation to return the bearing to another CLLocation.
I believe I'm doing something wrong with the formula (calculous is not my strong suit). The returned bearing is always off.
I've been looking at this question and tried applying the changes that were accepted as a correct answer and the webpage it references:
Calculating bearing between two CLLocationCoordinate2Ds
http://www.movable-type.co.uk/scripts/latlong.html
Thanks for any pointers. I've tried incorporating the feedback from that other question and I'm still just not getting something.
Thanks
Here's my category -
----- CLLocation+Bearing.h
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#interface CLLocation (Bearing)
-(double) bearingToLocation:(CLLocation *) destinationLocation;
-(NSString *) compassOrdinalToLocation:(CLLocation *) nwEndPoint;
#end
---------CLLocation+Bearing.m
#import "CLLocation+Bearing.h"
double DegreesToRadians(double degrees) {return degrees * M_PI / 180;};
double RadiansToDegrees(double radians) {return radians * 180/M_PI;};
#implementation CLLocation (Bearing)
-(double) bearingToLocation:(CLLocation *) destinationLocation {
double lat1 = DegreesToRadians(self.coordinate.latitude);
double lon1 = DegreesToRadians(self.coordinate.longitude);
double lat2 = DegreesToRadians(destinationLocation.coordinate.latitude);
double lon2 = DegreesToRadians(destinationLocation.coordinate.longitude);
double dLon = lon2 - lon1;
double y = sin(dLon) * cos(lat2);
double x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
double radiansBearing = atan2(y, x);
return RadiansToDegrees(radiansBearing);
}
Your code seems fine to me. Nothing wrong with the calculous. You don't specify how far off your results are, but you might try tweaking your radian/degrees converters to this:
double DegreesToRadians(double degrees) {return degrees * M_PI / 180.0;};
double RadiansToDegrees(double radians) {return radians * 180.0/M_PI;};
If you are getting negative bearings, add 2*M_PI to the final result in radiansBearing (or 360 if you do it after converting to degrees). atan2 returns the result in the range -M_PI to M_PI (-180 to 180 degrees), so you might want to convert it to compass bearings, using something like the following code
if(radiansBearing < 0.0)
radiansBearing += 2*M_PI;
This is a porting in Swift of the Category at the beginning:
import Foundation
import CoreLocation
public extension CLLocation{
func DegreesToRadians(_ degrees: Double ) -> Double {
return degrees * M_PI / 180
}
func RadiansToDegrees(_ radians: Double) -> Double {
return radians * 180 / M_PI
}
func bearingToLocationRadian(_ destinationLocation:CLLocation) -> Double {
let lat1 = DegreesToRadians(self.coordinate.latitude)
let lon1 = DegreesToRadians(self.coordinate.longitude)
let lat2 = DegreesToRadians(destinationLocation.coordinate.latitude);
let lon2 = DegreesToRadians(destinationLocation.coordinate.longitude);
let dLon = lon2 - lon1
let y = sin(dLon) * cos(lat2);
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon);
let radiansBearing = atan2(y, x)
return radiansBearing
}
func bearingToLocationDegrees(destinationLocation:CLLocation) -> Double{
return RadiansToDegrees(bearingToLocationRadian(destinationLocation))
}
}
Here is another implementation
public func bearingBetweenTwoPoints(#lat1 : Double, #lon1 : Double, #lat2 : Double, #lon2: Double) -> Double {
func DegreesToRadians (value:Double) -> Double {
return value * M_PI / 180.0
}
func RadiansToDegrees (value:Double) -> Double {
return value * 180.0 / M_PI
}
let y = sin(lon2-lon1) * cos(lat2)
let x = (cos(lat1) * sin(lat2)) - (sin(lat1) * cos(lat2) * cos(lat2-lon1))
let degrees = RadiansToDegrees(atan2(y,x))
let ret = (degrees + 360) % 360
return ret;
}
Working Swift 3 and 4
Tried so many versions and this one finally gives correct values!
extension CLLocation {
func getRadiansFrom(degrees: Double ) -> Double {
return degrees * .pi / 180
}
func getDegreesFrom(radians: Double) -> Double {
return radians * 180 / .pi
}
func bearingRadianTo(location: CLLocation) -> Double {
let lat1 = self.getRadiansFrom(degrees: self.coordinate.latitude)
let lon1 = self.getRadiansFrom(degrees: self.coordinate.longitude)
let lat2 = self.getRadiansFrom(degrees: location.coordinate.latitude)
let lon2 = self.getRadiansFrom(degrees: location.coordinate.longitude)
let dLon = lon2 - lon1
let y = sin(dLon) * cos(lat2)
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
var radiansBearing = atan2(y, x)
if radiansBearing < 0.0 {
radiansBearing += 2 * .pi
}
return radiansBearing
}
func bearingDegreesTo(location: CLLocation) -> Double {
return self.getDegreesFrom(radians: self.bearingRadianTo(location: location))
}
}
Usage:
let degrees = location1.bearingDegreesTo(location: location2)
This is an another CLLocation extension can be used in Swift 3 and Swift 4
public extension CLLocation {
func degreesToRadians(degrees: Double) -> Double {
return degrees * .pi / 180.0
}
func radiansToDegrees(radians: Double) -> Double {
return radians * 180.0 / .pi
}
func getBearingBetweenTwoPoints(point1: CLLocation, point2: CLLocation) -> Double {
let lat1 = degreesToRadians(degrees: point1.coordinate.latitude)
let lon1 = degreesToRadians(degrees: point1.coordinate.longitude)
let lat2 = degreesToRadians(degrees: point2.coordinate.latitude)
let lon2 = degreesToRadians(degrees: point2.coordinate.longitude)
let dLon = lon2 - lon1
let y = sin(dLon) * cos(lat2)
let x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon)
let radiansBearing = atan2(y, x)
return radiansToDegrees(radians: radiansBearing)
}
}
I use the Law of Cosines in Swift. It runs faster than Haversine and its result is extremely similar. Variation of 1 metre on huge distances.
Why do I use the Law of Cosines:
Run fast (because there is no sqrt functions)
Precise enough unless you do some astronomy
Perfect for a background task
func calculateDistance(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D) -> Double {
let π = M_PI
let degToRad: Double = π/180
let earthRadius: Double = 6372797.560856
// Law of Cosines formula
// d = r . arc cos (sin 𝜑A sin 𝜑B + cos 𝜑A cos 𝜑B cos(𝜆B - 𝜆A) )
let 𝜑A = from.latitude * degToRad
let 𝜑B = to.latitude * degToRad
let 𝜆A = from.longitude * degToRad
let 𝜆B = to.longitude * degToRad
let angularDistance = acos(sin(𝜑A) * sin(𝜑B) + cos(𝜑A) * cos(𝜑B) * cos(𝜆B - 𝜆A) )
let distance = earthRadius * angularDistance
return distance
}
Worth mentioning that if you are using Google map GMSMapView, there's an out-of-the-box solution using the GMSGeometryHeading method:
GMSGeometryHeading(from: CLLocationCoordinate2D, to: CLLocationCoordinate2D)
Returns the initial heading (degrees clockwise of North) at from of
the shortest path to to.
Implemented this in Swift 5. Focus is on accuracy, not speed, but it runs in real time np.
let earthRadius: Double = 6372456.7
let degToRad: Double = .pi / 180.0
let radToDeg: Double = 180.0 / .pi
func calcOffset(_ coord0: CLLocationCoordinate2D,
_ coord1: CLLocationCoordinate2D) -> (Double, Double) {
let lat0: Double = coord0.latitude * degToRad
let lat1: Double = coord1.latitude * degToRad
let lon0: Double = coord0.longitude * degToRad
let lon1: Double = coord1.longitude * degToRad
let dLat: Double = lat1 - lat0
let dLon: Double = lon1 - lon0
let y: Double = cos(lat1) * sin(dLon)
let x: Double = cos(lat0) * sin(lat1) - sin(lat0) * cos(lat1) * cos(dLon)
let t: Double = atan2(y, x)
let bearing: Double = t * radToDeg
let a: Double = pow(sin(dLat * 0.5), 2.0) + cos(lat0) * cos(lat1) * pow(sin(dLon * 0.5), 2.0)
let c: Double = 2.0 * atan2(sqrt(a), sqrt(1.0 - a));
let distance: Double = c * earthRadius
return (distance, bearing)
}
func translateCoord(_ coord: CLLocationCoordinate2D,
_ distance: Double,
_ bearing: Double) -> CLLocationCoordinate2D {
let d: Double = distance / earthRadius
let t: Double = bearing * degToRad
let lat0: Double = coord.latitude * degToRad
let lon0: Double = coord.longitude * degToRad
let lat1: Double = asin(sin(lat0) * cos(d) + cos(lat0) * sin(d) * cos(t))
let lon1: Double = lon0 + atan2(sin(t) * sin(d) * cos(lat0), cos(d) - sin(lat0) * sin(lat1))
let lat: Double = lat1 * radToDeg
let lon: Double = lon1 * radToDeg
let c: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: lat,
longitude: lon)
return c
}
I found that Haversine nailed the distance versus CLLocation's distance method, but didn't provide a bearing ready-to-use with CL. So I'm not using it for the bearing. This gives the most accurate measurement I've encountered from all the math I've tried. The translateCoord method will also precisely plot a new point given an origin, distance in meters, and a bearing in degrees.