繁体   English   中英

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

[英]ios - Spritekit - How to calculate the distance between two nodes?

我在屏幕上有两个sknodes。 计算距离的最佳方法是什么('作为乌鸦飞行的距离类型,我不需要矢量等)?

我有一个谷歌搜索在这里找不到涵盖这个的东西(关于sprite工具包的stackoverflow上没有太多的线程)

这是一个可以为你做的功能。 这是来自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);

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子类的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));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM