문제

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