Keep the Player’s Speed Consistent

When you first built the move action, you set a duration for the action using the speed parameter (yeah, I know). As a reminder, here’s the original method (it looks a little different now since you just added a direction parameter, too):

 func​ ​moveToPosition​(pos: ​CGPoint​, speed: ​TimeInterval​) {
 let​ moveAction = ​SKAction​.​move​(to: pos, duration: speed)
 run​(moveAction)
 }

The trouble with Blob’s movement is the duration of the action: it can’t be the same every time. When Blob is at the far left of the scene and travels to the far right, the duration of the action needs to be different than when he’s already halfway across the scene. In other words, Blob will need to go faster when he’s farther from his target location and slower when he’s closer to it.

Although you’re starting to get into the nitty-gritty of the game loop and how and when frames are updated, you don’t have to worry about that too much at this point. For now, you can leverage a little math to solve this problem.

Open the GameScene.swift file and add a new property to hold the player’s base speed:

 let​ playerSpeed: ​CGFloat​ = 1.5

Then, modify the touchDown(atPoint:) method so that it matches this:

 func​ ​touchDown​(atPoint pos : ​CGPoint​) {
 // Calculate the speed based on current position and tap location
 let​ distance = ​hypot​(pos.x-player.position.x, pos.y-player.position.y)
 let​ calculatedSpeed = ​TimeInterval​(distance / playerSpeed) / 255
 // print(" distance: (distance) calculatedSpeed: (calculatedSpeed)")
 
 if​ pos.x < player.position.x {
  player.​moveToPosition​(pos: pos, direction: ​"L"​, speed: calculatedSpeed)
  } ​else​ {
  player.​moveToPosition​(pos: pos, direction: ​"R"​, speed: calculatedSpeed)
  }
 }

This code uses another built-in function, hypot(),[27] and some math to calculate the speed value based on where the player node is currently located and where it’s headed. The hypot() function uses a bit of trigonometry to calculate the distance between the two points. Remember, the value stored in speed is used to determine the duration of the move action; in this case, moving the player node from point A to point B.

Build and run the project. Notice that Blob’s movement speed is now consistent regardless of where he starts or where he’s going.

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

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