mardi 25 août 2015

AND (&&) operator not working as expected in SWIFT

Im trying to randomly generate nodes on the screen without overlapping so I decided to find the range/distance of each node from each other and continuously randomly generate a position where the range from each node is greater than 100, once the range is over 100 it'll break out of the while loop and add the node to the view

    var p2Dp1: CGFloat = 0
    var p3Dp1: CGFloat = 0
    var p3Dp2: CGFloat = 0

    planet1.position = CGPoint(x: Int(arc4random_uniform(220) + 80), y: Int(arc4random_uniform(500) + 100))

    while p2Dp1 < 100.0 {

        planet2.position = CGPoint(x: Int(arc4random_uniform(220) + 80), y: Int(arc4random_uniform(500) + 100))
        p2Dp1 = SDistanceBetweenPoints(planet2.position, p2: planet1.position)
        print(" planet 2 distance from 1: \(p2Dp1) ")

    }

    while p3Dp1 < 100.0 && p3Dp2 < 100.0 {

        planet3.position = CGPoint(x: Int(arc4random_uniform(220) + 80), y: Int(arc4random_uniform(500) + 100))
        p3Dp1 = SDistanceBetweenPoints(planet3.position, p2: planet1.position)
        print(" planet 3 distance from 1: \(p3Dp1) ")
        p3Dp2 = SDistanceBetweenPoints(planet3.position, p2: planet2.position)
        print(" planet 3 distance from 2: \(p3Dp2) ")

    }

    self.addChild(planet1)
    self.addChild(planet2)
    self.addChild(planet3)

it starts by randomly giving the first node(planet1) a position on the view and then randomly give node2(planet2) a position where the distance from planet 1 and 2 are greater than 100. The first while loops seems to be working fine, its the second while loops thats giving me trouble. According to the console, the "&&" operator doesn't seem to be working

Console/Log:

planet 2 distance from 1: 96.1665222413705 planet 2 distance from 1: 185.407658957229 planet 3 distance from 1: 136.30847369111 planet 3 distance from 2: 55.1724568965349 EWWWW WE'RE TOUCHING

I set up the didBeginContact(contact: SKPhysicsContact) where it prints out if contact has happened

this is the method im using to find the distance:

func SDistanceBetweenPoints(p1: CGPoint, p2: CGPoint) -> CGFloat {

    return hypot(p2.x - p1.x, p2.y - p1.y);
}

can someone please tell me what I might be doing wrong? I'm planning to add 5 planets in total but just for now im testing it out with 3




Aucun commentaire:

Enregistrer un commentaire