ios – Spritekit – 如何计算两个节点之间的距离?

我在屏幕上有两个sknode。 什么是计算距离的最好方法('如同​​乌鸦'的距离types,我不需要一个向量等)?

我有一个谷歌和search在这里,找不到覆盖这个(有关sprite工具包stackoverflow上没有太多的线程)

这是一个可以为你做的function。 这是从一个苹果的冒险示例代码:

CGFloat SDistanceBetweenPoints(CGPoint first, CGPoint second) { return hypotf(second.x - first.x, second.y - first.y); } 

从你的代码中调用这个函数:

 CGFloat distance = SDistanceBetweenPoints(nodeA.position, nodeB.position); 

joshd和Andrey Gordeev都是正确的,而Gordeev的解决scheme则说明了这个hypotf函数的作用。

但平方根函数是一个昂贵的函数。 如果您需要知道实际距离,则必须使用它,但如果您只需要相对距离,则可以跳过平方根。 你可能想知道哪个精灵是最接近的,还是最靠前的,或者只要有精灵在半径范围内。 在这些情况下,只是比较距离的平方。

 - (float)getDistanceSquared:(CGPoint)p1 and:(CGPoint)p2 { return pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2); } 

为了计算SKScene子类的update:方法中是否存在任何精灵在视图中心的半径范围内:

 -(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. }; } } 

另一个快速的方法,也是因为我们正在处理距离,我加了abs(),以便结果总是正面的。

 extension CGPoint { func distance(point: CGPoint) -> CGFloat { return abs(CGFloat(hypotf(Float(point.x - x), Float(point.y - y)))) } } 

不是迅捷吗?

迅速:

 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); } } 

勾股定理:

 - (float)getDistanceBetween:(CGPoint)p1 and:(CGPoint)p2 { return sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p1.y,2)); }