【问题标题】:ios - Spritekit - How to calculate the distance between two nodes?ios - Spritekit - 如何计算两个节点之间的距离?
【发布时间】:2014-01-21 07:22:43
【问题描述】:

我在屏幕上有两个 sknode。计算距离的最佳方法是什么('as the crow flies' 类型的距离,我不需要矢量等)?

我用谷歌搜索并在这里搜索并找不到涵盖此内容的内容(stackoverflow 上没有太多关于 sprite kit 的线程)

【问题讨论】:

    标签: ios sprite-kit


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      斯威夫特盛大吗?

      【讨论】:

      • 这对我帮助很大!谢谢
      • abs() 有必要吗? hypot() 不总是返回非负值吗?
      【解决方案3】:

      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,它需要两个浮点数。
      • 这是一个绝妙的技巧,我以前从未想过!谢谢。
      【解决方案4】:

      斯威夫特:

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

      【讨论】:

      • 你会如何使用这个?我明白了重点:dx和dy的后半部分都传入了,但是self是什么,又是怎么来的呢?
      • @confused 因为这是一个扩展,我认为这增加了在 CGPoint 实例上调用 .distance() 的能力,所以你可以像这样使用它:var theDistance = point1.distance(point2)
      【解决方案5】:

      勾股定理:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-30
        • 1970-01-01
        • 2013-06-26
        • 2011-04-23
        相关资源
        最近更新 更多