SKNode convertPoint toNode & fromNode confusion?

后端 未结 4 1867
遇见更好的自我
遇见更好的自我 2020-12-23 10:06

I am a little confused by how the SKNode methods convertPoint:fromNode: and convertPoint:ToNode: are working, I have looked at the doc

4条回答
  •  旧巷少年郎
    2020-12-23 10:22

    - (CGPoint)convertPoint:(CGPoint)point fromNode:(SKNode *)node

    This essentially is saying: convert a point expressed in another node's coordinate system into the caller's(self) coordinate system. The key is that the point has to be expressed in the node's coordinate system for this to work. If you are using a sprite's position as the point, you will need to pass the sprite's parent node as the last argument.

    Example: To get the red square's position in the scene's coordinate system:

    CGPoint positionInScene = [self convertPoint:[redSprite position]
                                        fromNode:[self blueSprite]];
    

    [5, 5] in blueSprite's coordinate system --> [105, 205] in the scene's coordinate system

    Your Example:

    CGPoint positionInScene = [self convertPoint:[self position] 
                                        fromNode:[self redSprite]];
    

    [0, 0] in redSprite's coordinate system --> [105, 205] in the scene's coordinate system

    You ended up with the same result from your code, only because [self position] was [0, 0] and you used redSprite's coordinate system. Your initial try was close, you just needed to provide the coordinate system that redSprite's position was expressed in, which is the parent sprite's coordinate system; in this case, that's blueSprite.

    - (CGPoint)convertPoint:(CGPoint)point toNode:(SKNode *)node

    This method is very much the opposite of the first method. It will convert a point in the caller's coordinate system into another node's coordinate system. The key for this method is that the point given has to be expressed in the caller's coordinate system.

    Example: Let's say your scene received a touch at [125, 225], and you wanted to add a new sprite at that location, which happens to be within the bounding box of redSprite. So to add a new sprite as a child of redSprite, you need to get the touch's location in redSprite's coordinate system. To get that:

    CGPoint positionInRedSprite = [self convertPoint:touchLocation 
                                              toNode:[self redSprite]];
    

    [125, 225] in the scene's coordinate system --> [20, 20] in redSprite's coordinate system

提交回复
热议问题