【发布时间】:2014-01-21 07:22:43
【问题描述】:
我在屏幕上有两个 sknode。计算距离的最佳方法是什么('as the crow flies' 类型的距离,我不需要矢量等)?
我用谷歌搜索并在这里搜索并找不到涵盖此内容的内容(stackoverflow 上没有太多关于 sprite kit 的线程)
【问题讨论】:
标签: ios sprite-kit
我在屏幕上有两个 sknode。计算距离的最佳方法是什么('as the crow flies' 类型的距离,我不需要矢量等)?
我用谷歌搜索并在这里搜索并找不到涵盖此内容的内容(stackoverflow 上没有太多关于 sprite kit 的线程)
【问题讨论】:
标签: ios sprite-kit
这是一个可以为您完成的功能。这是来自 Apple 的 Adventure 示例代码:
CGFloat SDistanceBetweenPoints(CGPoint first, CGPoint second) {
return hypotf(second.x - first.x, second.y - first.y);
}
从您的代码中调用此函数:
CGFloat distance = SDistanceBetweenPoints(nodeA.position, nodeB.position);
【讨论】:
另一种快速的方法,也是因为我们正在处理距离,我添加了 abs() 以便结果始终为正。
extension CGPoint {
func distance(point: CGPoint) -> CGFloat {
return abs(CGFloat(hypotf(Float(point.x - x), Float(point.y - y))))
}
}
斯威夫特盛大吗?
【讨论】:
joshd 和 Andrey Gordeev 都是正确的,Gordeev 的解决方案说明了 hypotf 函数的作用。
但是平方根函数是一个昂贵的函数。如果您需要知道实际距离,则必须使用它,但如果您只需要相对距离,则可以跳过平方根。您可能想知道哪个精灵最近或最远,或者是否有任何精灵在半径内。在这些情况下,只需比较距离的平方。
- (float)getDistanceSquared:(CGPoint)p1 and:(CGPoint)p2 {
return pow(p2.x - p1.x, 2) + pow(p2.y - p1.y, 2);
}
要使用它来计算是否有任何精灵在更新中距离视图中心的半径范围内:SKScene 子类的方法:
-(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.
};
}
}
【讨论】:
(p2.x-p1.y)*(p2.x-p1.y) 可以比pow 有很大的性能改进,因为pow 意味着接受两个双打。
powf,它需要两个浮点数。
斯威夫特:
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);
}
}
【讨论】:
var theDistance = point1.distance(point2)
勾股定理:
- (float)getDistanceBetween:(CGPoint)p1 and:(CGPoint)p2 {
return sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p1.y,2));
}
【讨论】: