1

我在 SpriteKit 周围闲逛并遇到了一些奇怪的事情,即我只是添加SKShapeNode了应该在 iPhone 上全屏显示的矩形

override func didMoveToView(view: SKView) {
    let _box            = SKShapeNode(rectOfSize: self.frame.size)
    _box.strokeColor    = SKColor.blueColor()
    _box.fillColor      = SKColor.blueColor()
    _box.position       = CGPointMake(200, 200)
    _box.name           = "box"
    self.addChild(_box)

    let _player         = SKShapeNode(circleOfRadius: 50)
    _player.position    = CGPoint(x:CGRectGetMidX(self.frame), y:CGRectGetMidY(self.frame))
    _player.fillColor   = SKColor.redColor()
    _player.strokeColor = SKColor.redColor()
    _player.name        = "player"
    _player.physicsBody = SKPhysicsBody(circleOfRadius: 50)
    _player.physicsBody?.dynamic = true
    _player.physicsBody?.allowsRotation = false
    self.addChild(_player)

    let _ground         = SKShapeNode(rectOfSize: CGSizeMake(self.frame.width, 20))
    _ground.name        = "ground"
    _ground.position    = CGPointMake(0, 0)
    _ground.fillColor   = SKColor.greenColor()
    _ground.strokeColor = SKColor.greenColor()
    _ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.width, 20))
    _ground.physicsBody?.dynamic = false
    self.addChild(_ground)
}

我的视图以这种方式初始化 override func viewDidLoad() { super.viewDidLoad() }

override func viewWillLayoutSubviews() {
    super.viewWillLayoutSubviews()
    if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
        // Configure the view.
        let skView = self.view as SKView
        skView.showsFPS = true
        skView.showsNodeCount = true

        /* Sprite Kit applies additional optimizations to improve rendering performance */
        skView.ignoresSiblingOrder = true

        /* Set the scale mode to scale to fit the window */
        scene.scaleMode = .AspectFill

        skView.presentScene(scene)
    }

}

生成的场景如下所示:screenshot

所有节点都移到左下角。基本上矩形形状的左下角超出范围(我通过将蓝色形状定位到 (200, 200) 而不是 (0, 0) 进行了检查 - 并且左下角仍然超出屏幕框架。

场景的锚点设置为 (0, 0) 所以基本上它看起来像我,它设置形状中心点的位置。

定义节点左下角位置而不是中点的最佳方法是什么?

4

2 回答 2

2
_box.position       = CGPointMake(self.size.width*.5, self.size.height*.5)

这会将精灵的中心定位在屏幕的中心。

于 2014-11-05T15:52:25.263 回答
1

如果您使用贝塞尔路径或 CGPath 创建形状,则可以指定其“锚点”的位置,路径的原点指定路径的左下角。例如,

    UIBezierPath* bezierPath = [UIBezierPath bezierPathWithRect: CGRectMake(0, 0, 50, 50)];
    SKShapeNode *shape = [SKShapeNode node];
    shape.path = bezierPath.CGPath;
    shape.fillColor = [SKColor blueColor];

此外,如果您的部署目标是 iOS 8,您可以使用

    SKShapeNode *shape = [SKShapeNode shapeNodeWithRect:CGRectMake(0, 0, 50, 50)];
    shape.fillColor = [SKColor blueColor];
于 2014-11-05T16:46:56.467 回答