简体   繁体   English

在两点之间添加块。 SpriteKit

[英]Add block between two points. SpriteKit

I am trying to add a SKNode between two points like picture below. 我试图在SKNode之间添加一个SKNode ,如下图所示。

在此处输入图片说明

What I have: 我有的:

    1. I count the distance between those two points with this code (works fine): 我用这段代码计算这两点之间的距离(可以正常工作):

        func distanceCount(_ point: CGPoint) -> CGFloat { return abs(CGFloat(hypotf(Float(point.x - x), Float(point.y - y)))) } 
    1. Then I count the middle point(also works fine) 然后我计算中间点(也很好)

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

Finally this function adds my object ( SKNode ) : 最后,此函数添加了我的对象( 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

    }

Summary : My addBlock function adds object with right width and centred on the right place , but angle is wrong. 摘要 :我的addBlock函数添加宽度正确且居中于正确位置的对象,但是角度是错误的。

Note : I have tried to create functions which should count the angle but they were all wrong :/ . 注意 :我试图创建应该计算角度的函数,但是它们都是错误的:/。

My question: How can I get the right angle , or is there some other how can I reach my goal? 我的问题:如何获得正确的角度,或者还有其他方法可以达到我的目标吗?

If you need more details just let me know. 如果您需要更多详细信息,请告诉我。

Thank you :) 谢谢 :)

Midpoint 中点

The midpoint between 2 points A and B is defined as 2点AB之间的中点定义为

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

CGPoint Extension CGPoint扩展

So let's create and extension of CGPoint to easily build a Midpoint starting from 2 points 因此,让我们创建和扩展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
    }
}

Test 测试

Now let's test it 现在让我们测试一下

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}

Looks good right? 看起来不错吧?

Wrap up 包起来

Now given your 2 points you just need to calculate the midpoint and assign it to the position of your SKNode . 现在给定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