沿着其中心旋转SKShapeNode

我有一个SKShapeNode(在这种情况下是矩形),我试图沿着它的中心旋转。 但是它沿着屏幕的左下angular旋转。 由于我无法为SKShapeNode设置定位点,我怎样才能达到我的要求(沿着其中心旋转形状)。 这是我正在尝试的代码。

let rectangle = SKShapeNode() rectangle.path = UIBezierPath(rect: CGRectMake(view.frame.width/4, view.frame.height/2, view.frame.width/2, view.frame.width/2)).CGPath rectangle.fillColor = UIColor.yellowColor() rectangle.strokeColor = UIColor.yellowColor() let oneRevolution = SKAction.rotateByAngle(360, duration: 100.0) let repeat = SKAction.repeatActionForever(oneRevolution) rectangle.runAction(repeat) 

在这里输入图像说明

你看了SKShapeNode文档: https : //developer.apple.com/library/IOs/documentation/SpriteKit/Reference/SKShapeNode_Ref/index.html

尝试使用:

 shapeNodeWithPath:centered: 

select是为居中。

如果是,则path被转换,以便path边界框的中心位于节点的原点; 否则path相对于节点的原点。

 SKSpriteNode rectangle = [SKSpriteNode spriteWithSize size: CGSizeMake(20,20)]; 

你可以做一个同样的矩形作为一个spriteNode,它可以让你访问改变定位点。 我的语法可能会有点偏离,但我相信它也可以在构造函数中使用颜色。

当您创buildSKShapeNode时,您必须将其设置为以这种方式居中

 let shapePath = UIBezierPath(...) ... ... let shape = SKShapeNode(path: shapePath.cgPath, centered: true) 

这样SKShapeNode的锚点将成为中心点。

我们必须在应用旋转之前明确地居中SKShapeNode。

  import SpriteKit import PlaygroundSupport let bounds = CGRect(x: 0, y: 0, width: 400, height: 200) let skview = SKView(frame: bounds) PlaygroundPage.current.liveView = skview 

在下面的第一个和第二个示例中,通过在初始化矩形时设置xy参数,然后设置位置属性来完成此操作。

  let first = SKShapeNode(rect: CGRect(x:-20, y:-20, width: 40, height: 40)) first.position = CGPoint(x: 70, y: 30) let second = SKShapeNode(rect: CGRect(x:-20, y:-20, width: 40, height: 40)) second.position = CGPoint(x: 70, y: 30) second.zRotation = CGFloat.pi * 0.15 second.strokeColor = .red 

在下面的第三个示例中,通过在初始化形状时将centered设置centered true ,然后设置位置属性来完成此操作。

  let path = CGMutablePath(); path.move(to: CGPoint(x: 50,y: 10)) path.addLine(to: CGPoint(x: 90, y: 10)) path.addLine(to: CGPoint(x: 90, y: 50)) path.addLine(to: CGPoint(x: 50, y: 50)) path.addLine(to: CGPoint(x: 50, y: 10)) let third = SKShapeNode(path: path, centered: true); third.position = CGPoint(x: 70,y: 30); third.zRotation = CGFloat.pi * 0.35 third.strokeColor = .yellow let scene = SKScene(size: CGSize(width: 400, height: 200)) scene.scaleMode = SKSceneScaleMode.aspectFill scene.size = skview.bounds.size scene.addChild(first); scene.addChild(second); scene.addChild(third); skview.presentScene(scene);