开发者

iphone code - CGPoint question

开发者 https://www.devze.com 2022-12-15 08:38 出处:网络
i have 10 moving objects (UIImageView), is there a better way to write this code? - (void) jumpOnTimer {

i have 10 moving objects (UIImageView),

is there a better way to write this code?

    - (void) jumpOnTimer {

        jumpBall1.center = CGPointMake(jumpBall1.center.x+pos1.x,jumpBall1.center.y+pos1.y);

        if(jumpBall1.center.x > 60 || jumpBall1.center.x < 0)
            pos1.x = -pos1.x;
        if(jumpBall1.center.y > 211 || jumpBall1.center.y < 82)
            pos1.y = -pos1.y;

        jumpBall2.center = CGPointMake(jumpBall2.center.x+pos2.x,jumpBall2.cen开发者_JAVA百科ter.y+pos2.y);

        if(jumpBall2.center.x > 40 || jumpBall2.center.x < 0)
            pos2.x = -pos2.x;
        if(jumpBall2.center.y > 206 || jumpBall2.center.y < 82)
            pos2.y = -pos2.y;

and so on...


Judging by that code snippet, it looks like you have a single controller which "owns" the ten balls, and you want the balls to bounce around according to a set of rules that are unique to each ball. A more object-oriented approach would be as follows:

@interface JumpBallClass
{
    CGPoint center;
    CGPoint speed;

    CGPoint lowerLimit;
    CGPoint upperLimit;
}
@property (assign) CGPoint lowerLimit;
@property (assign) CGPoint upperLimit;
- (void)update;
@end

@implementation JumpBallClass
- (void)update
{
    center.x += speed.x;
    center.y += speed.y;

    if (center.x > upperLimit.x || center.x < lowerLimit.x)
    { speed.x = -speed.x; }
    if (center.y > upperLimit.y || center.y < lowerLimit.y)
    { speed.y = -speed.y; }
}
@end

This setup would allow you to configure all of the balls once, by setting their upper and lower limits:

[jumpBall1 setUpperLimit:CGPointMake(60, 211)];
[jumpBall1 setLowerLimit:CGPointMake(0, 82)];
...

And then simply calling update on each ball in your timer method:

- (void) jumpOnTimer {          

    [jumpBall1 update];          
    [jumpBall2 update];
    ...
}

You can simplify this even further by storing all of the balls in an NSArray:

NSArray * balls = [NSArray arrayWithObjects:jumpBall1, jumpBall2, ..., nil];

And then calling makeObjectsPerformSelector:

[balls makeObjectsPerformSelector:@selector(update)];


You can make an array of jumpBalls and then loop through each and do the code for that. You can do something like this:

JumpBallClass *myjumpballs[10];

for (i=0; i<10; i++) {
    myjumpballs[i].center = CGPointMake(myjumpballs[i].center.x+pos1.x,myjumpballs[i].center.y+pos1.y);

    if(myjumpballs[i].center.x > 60 || myjumpballs[i].center.x < 0)
        pos1.x = -pos1.x;
    if(myjumpballs[i].center.y > 211 || myjumpballs[i].center.y < 82)
        pos1.y = -pos1.y;
}


Looks like you're trying to manually animate. Have a look at using UIView animations instead

0

精彩评论

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