Use Constraints to Limit Movement

At the moment, the player node moves to the tap location instead of staying on the platform. There’s a way to fix this problem using constraints and the SKConstraint class.

With constraints, you can restrict a node’s movement to a specific area. In this case, you need to limit the player.position.y value to keep Blob firmly on the platform.

Open the Player.swift file and add a new method above the walk() method:

 func​ ​setupConstraints​(floor: ​CGFloat​) {
 let​ range = ​SKRange​(lowerLimit: floor, upperLimit: floor)
 let​ lockToPlatform = ​SKConstraint​.​positionY​(range)
 
  constraints = [ lockToPlatform ]
 }

This new method sets up a range with an upper and lower limit using the values you pass in for the lowerLimit and upperLimit parameters.

Go back to the GameScene.swift file, and where you set up the player node, add the following line above the line that adds that node to the scene:

 player.​setupConstraints​(floor: foreground.frame.maxY)

This line of code calls the new method and passes in the foreground frame’s maxY value, which it uses to keep the player node’s position.y value constrained to the platform.

Build and run the project, and tap anywhere you’d like.

images/AddingAnimationAndMovementWithActions/spritekit-build-04.png

Notice that no matter where you tap, Blob stays firmly planted on top of the platform. But don’t celebrate yet. You need to work out the next problem: Blob’s inability to pay attention to where he’s going. Silly, Blob, what are you thinking?

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset