Set the Player’s Direction Using Scales

The next problem you need to fix is Blob’s inability to switch direction visually. At the moment, Blob only faces in one direction regardless of where he’s headed. You can fix Blob’s misguided behavior using the xScale property of the node.

First, open the Player.swift file and modify the moveToPosition(pos:direction:speed:) method to match the following:

 func​ ​moveToPosition​(pos: ​CGPoint​, direction: ​String​, speed: ​TimeInterval​) {
 switch​ direction {
 case​ ​"L"​:
  xScale = -​abs​(xScale)
 default​:
  xScale = ​abs​(xScale)
  }
 
 let​ moveAction = ​SKAction​.​move​(to: pos, duration: speed)
 run​(moveAction)
 }

The switch statement evaluates the value in the direction parameter (R=Right/L=Left) and adjusts the node’s xScale property accordingly:

  • direction = "R": Sets the xScale property value to a positive number.
  • direction = "L": Sets the xScale property value to a negative number.

Setting the value to positive or negative is handled with the built-in abs() method,[26] which returns an absolute value. You’re using an absolute value to ensure that you’re always starting with a positive number. You then convert that positive value to a negative value only when necessary.

Next, open the GameScene.swift file, and in the touchDown(atPoint:) method, modify the call that moves the player:

 if​ pos.x < player.position.x {
  player.​moveToPosition​(pos: pos, direction: ​"L"​, speed: 1.0)
 } ​else​ {
  player.​moveToPosition​(pos: pos, direction: ​"R"​, speed: 1.0)
 }

This code checks if the touch location (pos.x) is less than the player’s current x-position (player.x). If it is, that means Blob is headed left; otherwise, Blob is headed right.

Build and run the project to test Blob’s new superpower of looking where he’s going as shown in the image.

images/AddingAnimationAndMovementWithActions/spritekit-build-05.png

Great, you’re almost done. The last thing to fix is Blob’s inconsistent speed problem.

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

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