0ndre_ 0ndre_ - 1 year ago 77
Swift Question

Add block between two points. SpriteKit

I am trying to add a

between two points like picture below.

enter image description here

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

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

Answer Source

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

atan2(p2.y-p1.y, p2.x-p1.x)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download