Confusion about coordinates, frames & child nodes in SpriteKit on iOS?

依然范特西╮ 提交于 2019-12-05 04:22:30

You are creating the shape node using the sprite's frame, which is in scene coordinates. Because the shape will be a child of the sprite, you should create the node in the sprite's coordinates. For example, if you create the SKShapeNode with spaceship's size

let debugFrame = SKShapeNode(rectOfSize: spaceship.size)

instead of using the spaceship's frame, debugFrame will be centered on the spaceship regardless of when you set the ship's position. Also, debugFrame will scale/move appropriately with the ship.

In response to your 'I don't get it'. Your code is ok but has a logical problem. The 'frame' is counted relative to the parent coordinates. Please realize that the parent of the spaceship and the parent of the debug window are different in your code.

Two ways to resolve your problem:

  1. Add a zero offset for the debug window and use the spaceship as the parent. The advantage of this is that the debug window will move, scale with the spaceship: let rectDebug = CGRectMake( 0, 0, spaceship.frame.size.width, spaceship.frame.size.height) let debugFrame = SKShapeNode(rect:rectDebug) spaceship.addChild(debugFrame)
  2. Add the debug window with the spaceship 'frame' coordinates to the parent of the spaceship (which is 'self'). The disadvantage of this, is that you have to move, scale the debug window yourself in the code, since it will not be attached to the spaceship.: let debugFrame = SKShapeNode(rect:spaceship.frame) self.addChild(debugFrame)

Both solutions are widely used. You should chose whichever is better for you in your case. Three other problems might come up:

1.There might be code errors in my code, I just typed these into the web window directly without xcode syntax checking.

2.The anchor points of the two objects could be different. So you might need alignment in your code for this.

3.The zPosition of the objects should also be taken into consideration, so these objects will not be hidden under some other objects.

In response to the problem you are trying to solve, perhaps showPhysics would help:

    skView.showsFPS = YES;
    skView.showsNodeCount = YES;
    skView.showsPhysics = YES;

This is almost the same problem as in the other question you mentioned. frame is a property that contains a position and a size. Both of them are subject to scaling of their ancestor node. Read section "A Node Applies Many of Its Properties to Its Descendants" in https://developer.apple.com/library/ios/documentation/GraphicsAnimation/Conceptual/SpriteKit_PG/Nodes/Nodes.html#//apple_ref/doc/uid/TP40013043-CH3-SW13

Again : never apply scaling to a node, never move a node before having fully constructed its hierarchy, except if you want some special or weird effect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!