2014-10-09 83 views
5

我有一個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

回答

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

可以做出相同的矩形作爲spriteNode這將讓您獲得改變anchorpoint。我的語法可能會有點偏離,但我相信它也可以在構造函數中使用顏色。

+1

糾正了這個問題。 – 2014-10-10 03:46:04

0

當您創建SKShapeNode你必須將其設置爲中心這樣:

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

這樣的SKShapeNode的錨點將是中心點。

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);