问题
I have two sknodes on the screen. What is the best way to calculate the distance ('as the crow flies' type of distance, I don't need a vector etc)?
I've had a google and search on here and can't find something that covers this (there aren't too many threads on stackoverflow about sprite kit)
回答1:
Here's a function that will do it for you. This is from an Apple's Adventure example code:
CGFloat SDistanceBetweenPoints(CGPoint first, CGPoint second) {
return hypotf(second.x - first.x, second.y - first.y);
}
To call this function from your code:
CGFloat distance = SDistanceBetweenPoints(nodeA.position, nodeB.position);
回答2:
joshd and Andrey Gordeev are both correct, with Gordeev's solution spelling out what the hypotf function does.
But the square root function is an expensive function. You'll have to use it if you need to know the actual distance, but if you only need relative distance, you can skip the square root. You may want to know which sprite is closest, or furtherest, or just if any sprites are within a radius. In these cases just compare distance squared.
- (float)getDistanceSquared:(CGPoint)p1 and:(CGPoint)p2 {
return pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2);
}
To use this for calculating if any sprites are within a radius from the center of the view in the update: method of an SKScene subclass:
-(void)update:(CFTimeInterval)currentTime {
CGFloat radiusSquared = pow (self.closeDistance, 2);
CGPoint center = self.view.center;
for (SKNode *node in self.children) {
if (radiusSquared > [self getDistanceSquared:center and:node.position]) {
// This node is close to the center.
};
}
}
回答3:
Another swift method, also since we are dealing with distance, I added abs() so that the result would always be positive.
extension CGPoint {
func distance(point: CGPoint) -> CGFloat {
return abs(CGFloat(hypotf(Float(point.x - x), Float(point.y - y))))
}
}
Ain't swift grand?
回答4:
Swift:
extension CGPoint {
/**
Calculates a distance to the given point.
:param: point - the point to calculate a distance to
:returns: distance between current and the given points
*/
func distance(point: CGPoint) -> CGFloat {
let dx = self.x - point.x
let dy = self.y - point.y
return sqrt(dx * dx + dy * dy);
}
}
回答5:
Pythagorean theorem:
- (float)getDistanceBetween:(CGPoint)p1 and:(CGPoint)p2 {
return sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p1.y,2));
}
来源:https://stackoverflow.com/questions/21251706/ios-spritekit-how-to-calculate-the-distance-between-two-nodes