Adding Gravity behavior to multiple objects in Swift

I am creating a game that has many square blocks floating around the screen, bouncing off each other, walls, etc. until they are destroyed. I currently have a master UIGravityBehavior

and I add each square (a class UIView

called SquareView) as it is created, and then remove it when it is destroyed. But I think I should be doing it inside the SquareView object. Here's the relevant code:

class ViewController: UIViewController, UICollisionBehaviorDelegate  {
    var gravity: UIGravityBehavior!

      

...

// next sequence adds a square
let newSquare = SquareView()
newSquare.createSquare(touch.locationInView(view).x, y: touch.locationInView(view).y)
view.addSubview(newSquare)
gravity.addItem(newSquare)

      

...

// this removes a square
gravity.removeItem(currentSquare)

      

Therefore, I believe I should move this code outside ViewController

of my definition of my SquareView class:

func createSquare(x: CGFloat, y: CGFloat){
    self.backgroundColor = color[touchCount]
    self.frame = CGRect(x: x, y: y, width: size[touchCount], height: size[touchCount])
}

      

By the way, I am doing the same with UICollisionBehavior

and guess this is not optimal either.

Any help would be great!

+3


source to share





All Articles