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)
}
}
I have a crosshair on the screen and i can move it using touchesmoved as shown above, but my problem is i don't know how to prevent it from going of the screen. there is the fmaxf
& fminf
but i am not entirely sure how to use them, any help would be much appreciated.
You can limit the node
inside the coordinates using the following code. The following code only checks if the position of the sprite is within the bounds. I assumed the position is at the centre of the sprite.
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)
}
}