开发者

Objective C: SetNeedsDisplay

开发者 https://www.devze.com 2023-02-06 06:40 出处:网络
I\'ve been reading this book on game programming, but the examples are not th开发者_C百科at great. I\'m working on one that calls [self setNeedsDisplay] but it cause the app the crash.

I've been reading this book on game programming, but the examples are not th开发者_C百科at great. I'm working on one that calls [self setNeedsDisplay] but it cause the app the crash.

This is all the code I have, copied verbatim from the book:

-(void)awakeFromNib {
//start timer that will fire every second
[car setAlpha:0];
[road setAlpha:0];
currentImage = [UIImage imageNamed:@"road.png"];

//start timer that fires every second
[NSTimer scheduledTimerWithTimeInterval:(1.0) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];

//start timer that fires every hundreth of a second
[NSTimer scheduledTimerWithTimeInterval:(0.01) target:self selector:@selector(onTimerRoad) userInfo:nil repeats:YES];
}

-(void)onTimerRoad
{   
    int tileIndex;
tileIndex += 1;
[self setNeedsDisplay];
}

-(void)onTimer {
[self update];
[self draw];
}

-(void)update {
[self updateRoad];
}

-(void)updateRoad {
[self randomRoadUpdate];
}

-(void)randomRoadUpdate {
int distance = (random() % 11) -5;
CGPoint oldPosition = road.center;
if (oldPosition.x + distance < 96 || oldPosition.x + distance > 224)
    return;
road.center = CGPointMake(oldPosition.x + distance, oldPosition.y);
}

-(void)draw {

}

- (id) initWithFrame:(CGRect)frame {
if (self = [super initWithFrame:frame]) {
    //init code
}
return self;
}

-(void)drawRect:(CGRect)rect {
CGImageRef image = CGImageRetain(currentImage.CGImage);
CGRect imageRect;
imageRect.origin = CGPointMake(160, 240);
imageRect.size = CGSizeMake(320.0, 480.0);
CGContextRef uiContext = UIGraphicsGetCurrentContext();
CGContextClipToRect(uiContext, CGRectMake(0.0, 0.0, rect.size.width, rect.size.height));
CGContextDrawTiledImage(uiContext, imageRect, image);

}


Turns out instead of [self setNeedsDisplay] I need to do [self.view setNeedsDisplay]

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号