Reputation: 12444
Currently I am trying to check the screen boundaries by seeing if a CCSprite crossed the top or bottom of the screen. The thing is, I really want to combine the 2 below if statements into 1 statement. Anyway the only difficult thing I am going to have to do is the following. What I do below is move the CCSprite 1 point inwards to enforce the actual screen boundary. But I just do not see how I can do that with one if statement.
Anyway here is the method:
- (void)checkScreenBoundaries {
CGSize size = [[CCDirector sharedDirector] winSize];
if (sprite.position.y <= 0) {
sprite.position = ccp(sprite.position.x, 1);
died = YES;
} else if (sprite.position.y >= size.height) {
sprite.position = ccp(sprite.position.x, size.height - 1);
died = YES;
}
}
Can anyone show me how I can combine these two if's into 1?
Thanks!
Upvotes: 0
Views: 114
Reputation: 385500
CGFloat yNew = MAX(1, MIN(sprite.position.y, size.height - 1));
if (yNew != sprite.position.y) {
sprite.position = ccp(sprite.position.x, yNew);
died = YES;
}
Upvotes: 2
Reputation: 6942
if ((sprite.position.y <= 0) || (sprite.position.y >= size.height)) {
sprite.position = ccp(sprite.position.x, (sprite.position.y <= 0) ? 1 : (size.height - 1));
died = YES;
}
Upvotes: 2