0ndre_
0ndre_

Reputation: 3631

Add block between two points. SpriteKit

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

enter image description here

What I have:

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

Upvotes: 1

Views: 211

Answers (2)

Craig Siemens
Craig Siemens

Reputation: 13296

To get the angle between two points you'll need to use the following

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

Upvotes: 3

Luca Angeletti
Luca Angeletti

Reputation: 59536

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)

Upvotes: 3

Related Questions