Chapter 2: Challenge 2

For my game I need to modify some of the code that is used in this challenge. But I do not get the code and how it works. I am talking about this code:

//1
if let lastTouchLocation = lastTouchLocation {
let diff = lastTouchLocation - zombie.position
  if diff.length() <= zombieMovePointsPerSec * CGFloat(dt) {
    zombie.position = lastTouchLocation
    velocity = CGPoint.zero
  } else {
    move(sprite: zombie, velocity: velocity)
    rotate(sprite: zombie, direction: velocity)
  }
}

I do not get the first if statement. What does it mean?

In my case I am not using a touch location as a target to move the sprite to, instead I have a SKSpriteNode that is the target to which the zombie should walk to. Unfortunately I still miss the ‘click’ in my head. Does anyone can gibe me a helping hand?

Thanks so much in advance

The first statement means: there might be a “last touch location”. If there is, ‘unwrap’ it, so you can perform the following instructions knowing that there is a last touch location rather than that there might be one.

If you want to use a location other than the last touch location, such as a node position, then replace the references to ‘last touch location’ with the preferred location. If the preferred location is optional, you can unwrap it as here; if it’s known, then you don’t need the ‘if’ statement at all.

1 Like