简体   繁体   中英

Add block between two points. SpriteKit

I am trying to add a SKNode between two points like picture below.

在此处输入图片说明

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 ) :

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.

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

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

CGPoint Extension

So let's create and extension of CGPoint to easily build a Midpoint starting from 2 points

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM