Sunday, 29 September 2013

Keeping SKSpriteNode in bounds of screen

Keeping SKSpriteNode in bounds of screen

I am trying to check whether my SKSpriteNode will remain in bounds of the
screen during a drag gesture. I've gotten to the point where I am pretty
sure my logic toward approaching the problem is right, but my
implementation is wrong. Basically, before the player moves from the
translation, the program checks to see whether its in bounds. Here is my
code:
-(CGPoint)checkBounds:(CGPoint)newLocation{
CGSize screenSize = self.size;
CGPoint returnValue = newLocation;
if (newLocation.x <= self.player.position.x){
returnValue.x = MIN(returnValue.x,0);
} else {
returnValue.x = MAX(returnValue.x, screenSize.width);
}
if (newLocation.y <= self.player.position.x){
returnValue.y = MIN(-returnValue.y, 0);
} else {
returnValue.y = MAX(returnValue.y, screenSize.height);
}
NSLog(@"%@", NSStringFromCGPoint(returnValue));
return returnValue;
}
-(void)dragPlayer: (UIPanGestureRecognizer *)gesture {
CGPoint translation = [gesture translationInView:self.view];
CGPoint newLocation = CGPointMake(self.player.position.x +
translation.x, self.player.position.y - translation.y);
self.player.position = [self checkBounds:newLocation];
}
For some reason, my player is going off screen. I think my use of the MIN
& MAX macros may be wrong, but I am not sure.

No comments:

Post a Comment