2020-09-28

Checking all elements in an array in Swift against each other

For my app, I'm trying to determine whether the elements in an array of circle views overlap with each other. I have a for loop that iterates through the circle elements in the array, checks whether the element overlaps with the previous one, and if so; changes the element's position in the view:

func drawCircles(){
    for c in circles {
        c.center =  getRandomPoint()
        let prev = circles.before(c)
                
        if let prevCircleCenter = prev?.center {
            let dist = distance(prevCircleCenter, c.center)
            //50 = width of each circle
            if dist <= 50 {
              
                var newCenter = c.center
                var centersVector = CGVector(dx: newCenter.x - prevCircleCenter.x, dy: newCenter.y - prevCircleCenter.y)

                centersVector.dx *= 51 / dist
                centersVector.dy *= 51 / dist
                newCenter.x = prevCircleCenter.x + centersVector.dx
                newCenter.y = prevCircleCenter.y + centersVector.dy
                c.center = newCenter
            }
        }
    }
    
    for c in circles {
        self.view.addSubview(c)
    }
}

This is the method I'm using to check the previous element:

extension BidirectionalCollection where Iterator.Element: Equatable {
    typealias Element = Self.Iterator.Element


    func before(_ item: Element, loop: Bool = false) -> Element? {
        if let itemIndex = self.firstIndex(of: item) {
            let firstItem: Bool = (itemIndex == startIndex)
            if loop && firstItem {
                return self.last
            } else if firstItem {
                return nil
            } else {
                return self[index(before:itemIndex)]
            }
        }
        return nil
    }
}

I had tried adding an inner for-loop to re-check all whether the next and previous elements are overlapping, but that did not seem to work.

So, I guess I'm trying to figure out how to check each CircleView element in the array against each other to make sure they don't have an overlapping position.



from Recent Questions - Stack Overflow https://ift.tt/3mVprm0
https://ift.tt/eA8V8J

No comments:

Post a Comment