user7206517
user7206517

Reputation:

How can i check if two SKSpriteNodes are near each other?

How can i check if two SKSpriteNodes are near each other? like in a radius of 100. i am using the gamescene.swift and gamescene.sks.

Upvotes: 3

Views: 166

Answers (2)

Knight0fDragon
Knight0fDragon

Reputation: 16827

If you want to use built in SKPhysicsBody, then just set the body to a circle with radius of 100, then you can use the didBeginContact method when a contact occurs:

func setup()
{
    let physicsBody1 = SKPhysicsBody(circleOfRadius:100.0)
    physicsBody1.categoryBitMask = 1
    physicsBody1.collisionBitMask = 0
    physicsBody1.contactTestBitMask = 2
    sprite1.physicsBody = physicsBody1


    let physicsBody2 = SKPhysicsBody(circleOfRadius:100.0)
    physicsBody2.categoryBitMask = 2
    physicsBody2.collisionBitMask = 0
    physicsBody2.contactTestBitMask = 1
    sprite2.physicsBody = physicsBody2
}


func didBeginContact(contact:SKPhysicsContact)
{
  //find some tutorials to your liking, and do your contact code here
}

Upvotes: 0

Lou Franco
Lou Franco

Reputation: 89152

SKSpriteNode has a position property with the (x, y).

Distance between two positions is sqrt((x1-x2)^2 + (y1-y2)^2)

So:

let dist = sqrt(pow(sk1.position.x - sk2.position.x, 2.0) + pow(sk1.position.y - sk2.position.y, 2.0))
if dist < 100 {
    // they are close
}

This is center to center.

Based on @MartinR's comment, you could also

let dist = hypot(sk1.position.x - sk2.position.x, sk1.position.y - sk2.position.y)

Which does the distance function for you.

Upvotes: 1

Related Questions