yate-ge
2/7/2017 - 7:23 AM

SpriteKit:设置地图边界

SpriteKit:设置地图边界

func setupCamera() {
    guard let camera = camera, let view = view else { return }
    // 设置camera中心为主角
    let zeroDistance = SKRange(constantValue: 0)
    let playerConstraint = SKConstraint.distance(zeroDistance,
                                                 to: player)
    // 确定camera是否小于background
    let xInset = min(view.bounds.width/2 * camera.xScale,
                     background.frame.width/2)
    let yInset = min(view.bounds.height/2 * camera.yScale,
                     background.frame.height/2)
    
    // 绘制camera中心的活动范围(insertby后得到的rect的边长分别减少了2*dy和2*dx)
    let constraintRect = background.frame.insetBy(dx: xInset,
                                                  dy: yInset)
    // 设置camera的活动范围
    let xRange = SKRange(lowerLimit: constraintRect.minX,
                         upperLimit: constraintRect.maxX)
    let yRange = SKRange(lowerLimit: constraintRect.minY,
                         upperLimit: constraintRect.maxY)
    
    let edgeConstraint = SKConstraint.positionX(xRange, y: yRange)
    edgeConstraint.referenceNode = background
    // 后面的条件优先级大于前面的条件
    camera.constraints = [playerConstraint, edgeConstraint]
  }