如何从SpriteKit框架中从SKPhysicsBody获取六角形形状

问题描述:

我正在做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类的代码,你能检查一下,并且提供任何建议来获得六角形吗?谢谢 –

所有你需要做的是使用不同的初始化。您正在使用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 但是,它变得很糟糕 –

扩大对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 但是,它变得不合时宜 –