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

后端 未结 5 939
有刺的猬
有刺的猬 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.
            };
        }
    }
    
    0 讨论(0)
  • 2020-12-14 21:56

    Here's a function that will do it for you. This is from an Apple's Adventure example code:

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

    To call this function from your code:

    CGFloat distance = SDistanceBetweenPoints(nodeA.position, nodeB.position);
    
    0 讨论(0)
  • 2020-12-14 21:56

    Swift:

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-14 21:56

    Pythagorean theorem:

    - (float)getDistanceBetween:(CGPoint)p1 and:(CGPoint)p2 {
        return sqrt(pow(p2.x-p1.x,2)+pow(p2.y-p1.y,2));
    }
    
    0 讨论(0)
  • 2020-12-14 22:04

    Another swift method, also since we are dealing with distance, I added abs() so that the result would always be positive.

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

    Ain't swift grand?

    0 讨论(0)
提交回复
热议问题