沿其中心旋转SKShapeNode

时间:2014-10-09 17:19:40

标签: ios swift sprite-kit skshapenode

我有一个SKShapeNode(在这种情况下为矩形),我试图沿着它的中心旋转。然而,它沿着屏幕的左下角旋转。由于我无法为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)

enter image description here

4 个答案:

答案 0 :(得分:5)

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

尝试使用:

shapeNodeWithPath:centered:

为居中选择YES。

  

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

答案 1 :(得分:1)

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

您可以使用与spriteNode相同的矩形,这样您就可以更改anchorpoint。我的语法可能有些偏差,但我相信它也可以在构造函数中使用颜色。

答案 2 :(得分:0)

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

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

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

答案 3 :(得分: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

在下面的第三个示例中,这是通过在初始化形状时将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);
相关问题