簡體   English   中英

在兩點之間添加塊。 SpriteKit

[英]Add block between two points. SpriteKit

我試圖在SKNode之間添加一個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函數添加寬度正確且居中於正確位置的對象,但是角度是錯誤的。

注意 :我試圖創建應該計算角度的函數,但是它們都是錯誤的:/。

我的問題:如何獲得正確的角度,或者還有其他方法可以達到我的目標嗎?

如果您需要更多詳細信息,請告訴我。

謝謝 :)

中點

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的位置SKNode

let nodeA: SKNode = ...
let nodeB: SKNode = ...
let nodeC: SKNode = ...

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

要獲得兩點之間的角度,您需要使用以下內容

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM