【问题标题】:Add block between two points. SpriteKit在两点之间添加块。精灵套件
【发布时间】:2016-11-18 17:22:53
【问题描述】:

我正在尝试在两点之间添加SKNode,如下图所示。

我有什么:

    1. 我用这段代码计算这两点之间的距离(工作正常):

       func distanceCount(_ point: CGPoint) -> CGFloat {
       return abs(CGFloat(hypotf(Float(point.x - x), Float(point.y - y))))  }
      
    1. 然后我算中点(也可以)

        func middlePointCount(_ point: CGPoint) -> CGPoint {
        return CGPoint(x: CGFloat((point.x + x) / 2), y: CGFloat((point.y + y) / 2))
         }
      

最后这个函数添加了我的对象(SKNode):

func addBlock(_ size:CGSize, rotation:CGFloat, point: CGPoint) -> SKNode{

        let block = SKSpriteNode(color: UIColor.lightGray , size: size)
        block.physicsBody = SKPhysicsBody(rectangleOf: block.frame.size)
        block.position = point //This is my middle point
        block.physicsBody!.affectedByGravity = false
        block.physicsBody!.isDynamic = false
        block.zRotation = rotation 

        return block

    }

总结:我的addBlock 函数添加了正确宽度且居中于正确位置的对象,但角度错误。

注意:我尝试创建应该计算角度的函数,但它们都错了:/ .

我的问题:我怎样才能得到正确的角度,或者还有其他方法可以达到我的目标吗?

如果您需要更多详细信息,请告诉我。

谢谢你:)

【问题讨论】:

    标签: ios swift sprite-kit sknode


    【解决方案1】:

    要获得两点之间的角度,您需要使用以下方法

    atan2(p2.y-p1.y, p2.x-p1.x)
    

    【讨论】:

      【解决方案2】:

      中点

      两点AB 之间的中点定义为

      midpoint = {(A.x + B.x) / 2, (A.y + B.y) / 2}
      

      CGPoint 扩展

      所以让我们创建和扩展CGPoint,以便从2点开始轻松构建Midpoint

      extension CGPoint {
          init(midPointBetweenA a: CGPoint, andB b: CGPoint) {
              self.x = (a.x + b.x) / 2
              self.y = (a.y + b.y) / 2
          }
      }
      

      测试

      现在让我们测试一下

      let a = CGPoint(x: 1, y: 4)
      let b = CGPoint(x: 2, y: 3)
      
      let c = CGPoint(midPointBetweenA: a, andB: b) // {x 1,5 y 3,5}
      

      看起来不错吧?

      总结

      现在给定您的 2 个点,您只需计算中点并将其分配给您的 SKNode 的位置。

      let nodeA: SKNode = ...
      let nodeB: SKNode = ...
      let nodeC: SKNode = ...
      
      nodeC.position = CGPoint(midPointBetweenA: nodeA.position, andB: nodeB.position)
      

      【讨论】:

      • 当您开始编写关于 Swift Extensions 的 iBook 时,让我为您完成编辑、设计、插图和布局!传奇!
      • 有人说 Swift 是 POP,其他人说它是函数式的,创建者说它融合了十几种语言理念和制作通用系统语言的愿望......我怀疑写作能力具有令人难以置信的性能的扩展,别名使它像类固醇上的徽标。当然,长期服用大剂量的类固醇。有点像阿诺德之于特朗普。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-26
      • 2013-10-23
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2017-09-18
      相关资源
      最近更新 更多