将节点钳制到屏幕边界

Clamp node to screen bounds

 override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

        for touch: AnyObject in touches {
            let location = touch.locationInNode(self)
            let previousLocation = touch.previousLocationInNode(self)

            var translation = CGPointMake(location.x - previousLocation.x, location.y - previousLocation.y)
crossHair.position = CGPointMake(crossHair.position.x  + translation.x * 3, crossHair.position.y + translation.y * 3)
   }
    }

我在屏幕上有一个十字准线,我可以使用上面显示的 touchesmoved 移动它,但我的问题是我不知道如何防止它离开屏幕。有 fmaxf & fminf 但我不完全确定如何使用它们,任何帮助将不胜感激。

您可以使用以下代码限制坐标内的node。以下代码仅检查精灵的位置是否在边界内。我假设位置在精灵的中心。

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

    for touch: AnyObject in touches {
        let location = touch.locationInNode(self)
        let previousLocation = touch.previousLocationInNode(self)

        var translation = CGPointMake(location.x - previousLocation.x, location.y - previousLocation.y)
        var positionX : CGFloat = crossHair.position.x + translation.x * 3
        var positionY : CGFloat = crossHair.position.y + translation.y * 3

        if positionX < 0 {
            positionX = 0
        }
        else if positionX > self.size.width
        {
            positionX = self.size.width
        }

        if positionY < 0 {
            positionY = 0
        }
        else if positionY > self.size.height
        {
            positionY = self.size.height
        }

        crossHair.position = CGPointMake(positionX, positionY)

    }
}

获取十字准线位置后,检查是否不在屏幕外:

var x = crossHair.position.x;
var y = crossHair.position.y; 
if(crossHair.position.x > self.size.width) {
  x = self.size.width;
}
if(crossHair.position.x < 0) {
 x = 0;
}
if(crossHair.position.y > self.size.height) {
  y = self.size.height;
}
if(crossHair.position.y < 0) {
 y = 0;
}

crossHair.position = CGPointMake(x,y);