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

后端 未结 5 957
有刺的猬
有刺的猬 2020-12-14 21:19

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 go

5条回答
  •  一生所求
    2020-12-14 21:54

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

提交回复
热议问题