7

I have an SKShapeNode (rectangle in this case) which I am trying to rotate along its center. However it is rotating along the screen's bottom left point. Since I cannot set an anchor point for SKShapeNode, how can I achieve my requirement (to rotate the shape along its centre). This is the code I'm trying.

    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)

enter image description here

4

4 回答 4

5

您是否查看过 SKShapeNode 文档:https ://developer.apple.com/library/IOs/documentation/SpriteKit/Reference/SKShapeNode_Ref/index.html

尝试使用:

shapeNodeWithPath:centered:

选择 YES 居中。

如果是,则转换路径,使路径边界框的中心位于节点的原点;否则路径是相对于节点的原点的。

于 2014-10-13T04:58:26.720 回答
1
SKSpriteNode rectangle = [SKSpriteNode spriteWithSize size: CGSizeMake(20,20)];

您可以制作与 spriteNode 相同的矩形,这将使您可以更改锚点。我的语法可能有点偏离,但我相信它也可以在构造函数中使用颜色。

于 2014-10-09T18:29:18.243 回答
0

在应用旋转之前,我们必须明确地将 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

在下面的第三个示例中,这是通过在初始化形状时设置centeredtrue,然后设置位置属性来完成的。

    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);
于 2017-12-04T14:06:00.823 回答
0

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

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

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

于 2017-05-30T11:40:16.753 回答