2017-10-05 122 views
1

我正在做Swift中的iOS應用程序。我想顯示蘋果音樂泡泡的佈局。下面的代碼工作正常,以顯示佈局,但是,我想顯示六角形佈局,而不是圓形氣泡。如何從SpriteKit框架中從SKPhysicsBody獲取六角形形狀

任何人都可以建議/指導我,如何顯示六邊形佈局而不是圓形佈局。

在磁性類:

func configure() { 

     physicsWorld.gravity = CGVector(dx: 0, dy: 0) 
     physicsBody = SKPhysicsBody(edgeLoopFrom: {() -> CGRect in 
      var frame = self.frame 
      frame.size.width = CGFloat(magneticField.minimumRadius) 
      frame.origin.x -= frame.size.width/2 
      return frame 
     }()) 
     let strength = Float(max(size.width, size.height)) 
     let radius = strength.squareRoot() * 100 
     magneticField.region = SKRegion(radius: radius) 
     magneticField.minimumRadius = radius 
     magneticField.strength = strength 
     magneticField.position = CGPoint(x: size.width/2, y: size.height/2) 
    } 

在節點類:

public init(text: String?, image: UIImage?, color: UIColor, radius: CGFloat) { 
    super.init(circleOfRadius: radius) 

    self.physicsBody = { 
     let body = SKPhysicsBody(circleOfRadius: radius + 2) 
     body.allowsRotation = false 
     body.friction = 0 
     body.linearDamping = 3 
     return body 
    }() 
    self.fillColor = .white 
    self.strokeColor = .white 
    _ = self.sprite 
    _ = self.text 
    configure(text: text, image: image, color: color) 
} 
+0

你的代碼對我們沒有任何幫助,你只顯示一個物理體和一個磁場 – Knight0fDragon

+0

@ Knight0fDragon我也加了Node類的代碼,你能檢查一下,並且提供任何建議來獲得六角形嗎?謝謝 –

回答

1

所有你需要做的是使用不同的初始化。您正在使用super.init(circleOfRadius: radius)要製作六角形,只需使用super.init(path path:CGPath)其中path是一個六邊形形狀的CGPath。 (CGPath簡單易懂,只需用6點創建它的六邊形形狀,但大你需要它),那麼你可以走這條路,並通過做let body = SKPhysicsBody(polygonFrom:path)

就我個人把它交給物理體,您可能希望減少使用閉包的方式。 (let physicsBody = {...}())它們不保證立即觸發並可能導致併發問題。一個更好的辦法來糾正它會做在如果再讓聲明:

if let body = SKPhysicsBody(circleOfRadius: radius + 2) 
{   
    body.allowsRotation = false 
    body.friction = 0 
    body.linearDamping = 3 
    self.physicsBody = body 
} 
+0

在你旁邊:立即調用閉包與併發無關,並且確實立即調用。 'let foo = {...}()'和'let foo = someFunc()'有相同的效果,只是沒有'someFunc'的主體需要在其他地方定義。 – rickster

+0

@rickster,我將不得不經歷一些我的代碼,但我相信我在後臺線程上做這樣的事情時遇到了問題,導致我的閉包崩潰,因爲閉包期望一個不再存在的對象 – Knight0fDragon

+0

我試圖這樣做,就像下面讓lineWidth:CGFloat = 2 let hexaGonPath = roundedPolygonPath(rect:rectFrame,lineWidth:lineWidth,sides:6,cornerRadius:10,rotationOffset:CGFloat(M_PI/2.0))as! CGPath 但是,它變得很糟糕 –

1

擴大對KnightofDragon的答案,就可以計算出一個六邊形的6分與下列僞碼/數學:

PI = 3.14159 
for i in 0..<6 { 
    theta = i*2.0*PI/n; // angle to the ith vertex, in radians (not degrees) 
    x = radius * cos(theta) 
    y = radius * sin(theta) 
    vertex = centerPosition.x + x, centerPosition.y + y 
} 
+1

你可以做Float.pi,而不必擔心自己不斷變化,+1幫忙 – Knight0fDragon

+0

謝謝。我從兩個星期前的C++/openGL項目中剝離了它,並且承認沒有花太多精力將它轉換成Swift。 – AmandaR

+0

我試圖這樣做,就像下面讓lineWidth:CGFloat = 2 let hexaGonPath = roundedPolygonPath(rect:rectFrame,lineWidth:lineWidth,sides:6,cornerRadius:10,rotationOffset:CGFloat(M_PI/2.0))as! CGPath 但是,它變得不合時宜 –

相關問題