Fruity Crush Saga App Diary: Day 5

valigia piena di frutta

Having completed the swipe to swap it was time to update the model and animate the swap. This involved creating a new Swap struct. In Swift the struct is a value type versus a class which is a reference type. Here it makes sense to use a struct since the swap is inert and only stores data. The logic of handling the swap is not done by the swap itself. The detection of the swap is handled in the Game Scene and the real game logic is in the Game View Controller.

The Swap struct simply contains a fruitA and a fruitB property which are the from fruit to fruit values that the player wants to swap. The initializer sets these properties.

The GameScene needs a way to communicate back to the GameVC. This could be achieved in several different ways in Cocoa with Swift. Delegate Protocols would work but since its only one message between a View and VC we can use a closure.  A swipeHandler closure property is added to GameScene that takes a Swap object and returns nothing. The swipeHandler can also be nil and hence we make it into an optional. This property is implemented in the VC and assigned in the VC when the scene is presented.

In the GameScene where we tried to swap we use this swap handler and pass a Swap object. Then the GameVC will decide whether the swap is valid. If it is valid we’ll animate it which is a function in the GameScene we’ll call animateSwap(swap: completion:).  The animateSwap function will contain SKAction animation code that will move the fruit sprites in position ensure the original fruit will be rendered on top of the destination fruit.

The model also needs to be updated and this is handled in the level class with a performSwap(swap:) function that is called by the GameVC’s handleSwipe(swap:) function.

Running the current code allows the player to make valid swaps.

Next, we’ll highlight the fruits that the user want’s to swipe in order to provide a nice feedback effect.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s