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.

有帮助吗?

解决方案

Exactly, you mixed up MIN/MAX. The line MIN(x, 0) will return the lower value of x or 0, meaning the result will be 0 or less.

At one line you're using -returnValue.y which makes no sense.

You can (and should for readability) omit the if/else because MIN/MAX, if used correctly, make if/else unnecessary here.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top