Apple Game Frameworks and Technologies: Distance calc could be simpler for this point of the book (p 54)

The very top line of page 52 is let distance = hypot(pos.x-player.position.x, pos.y-player.position.y). As the text below the code snippet explains:

This code uses another built-in function, hypot(), 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.

The two points in question are the player sprite’s position and the position you tapped on. hypot is taking the 2d distance between the two points, but the player sprite is constrained to only move horizontally – on a single dimension. We could easily compute the distance along only the x axis.

The use of hypot adds some complexity and introduces a subtle bug to the movement. If you tap one inch to the right of the player sprite on the same Y level as it (so on the platform just right of it) the sprite moves over at the speed we expect. But if you tap one inch right of the player sprite, but at the top of the screen, then the sprite moves over much slower than the previous time. That’s because the diagonal from the player at the bottom of the screen up to the top of the screen is longer than the straight line distance when we tapped just to the right. This longer distance computes that we need more time to move that far. But since we are constrained to moving only along the X axis we end up moving the same distance either way. Just faster one way versus the other.

At this point in the book it might be simpler, easier to understand, and more accurate to just compute the distance with:

let distance = abs(pos.x - player.position.x)

3 Likes