Reputation: 449
I have a small method that I am calling to draw stars progressively as a game moves on. Here is the code:`
-(void)stars{
for (int i = 0; i < (ScoreNumber * 3); i++){
int starX = ((arc4random() % (320 - 0 + 1)) + 0);
int starY = ((arc4random() % (640 - 0 + 1)) + 0);
int starSize = ((arc4random() % (1 - 0 + 1)) + 1);
UIView *stars = [[UIView alloc] initWithFrame:CGRectMake(starX,starY, starSize, starSize)];
stars.alpha = (i / 5);
stars.backgroundColor = [UIColor whiteColor];
[self.view addSubview:stars];
}
}
The stars do show but each iteration through the loop it bugs out another UIImageView (main character) and resets it's position. Also the alpha values appear to not work at all and it appears to only use the value of 1 (full showing). Any advice (for a new programmer) would be appreciated.
Upvotes: 0
Views: 89
Reputation: 2049
The problem is that only the first 5 stars will have an alpha less than one:
-(void)stars{
for (int i = 0; i < (ScoreNumber * 3); i++){
int starX = ((arc4random() % (320 - 0 + 1)) + 0);
int starY = ((arc4random() % (640 - 0 + 1)) + 0);
int starSize = ((arc4random() % (1 - 0 + 1)) + 1);
UIView *stars = [[UIView alloc] initWithFrame:CGRectMake(starX,starY, starSize, starSize)];
stars.alpha = (i / 5); // ONCE THIS IS 5 (LIKELY WON'T TAKE LONG), ALPHA WILL BE 1 FOR ALL YOUR STARS
stars.backgroundColor = [UIColor whiteColor];
[self.view addSubview:stars];
}
}
Also, if a star is added to the superview on top of a current star and its alpha is actually less than 1, it will appear like it has more alpha than it actually does.
One fix might be to change 5 to a something bigger, like 25 or 50. It's hard to know what would be appropriate without knowing how big ScoreNumber
can be.
Edit:
Also, just realized another problem: you're dividing an int by an int, so alpha will be an int (not what you want). If you change the 5 to 5.0 (or 25.0 or 50.0), you'll get a float.
Hope it helps!
Upvotes: 0
Reputation: 5787
i is an integer in this case so the result will always be rounded to the nearest whole number. 0 while i < 5. Otherwise 1, 2, 3, etc. Instead you might want:
stars.alpha = (CGFloat)i / 5.0;
Although alpha will still be 1.0 or more after i >= 5.
Maybe you meant something like:
stars.alpha = 0.20 + (CGFloat)((i % 5) / 5.0;
That will give your stars alpha values between 0.2 and 1.0.
Upvotes: 1