iphone代码 - CGPoint问题

dan*_*_au 3 iphone objective-c

我有10个移动对象(UIImageView),
有没有更好的方法来编写这段代码?

    - (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.center.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...
Run Code Online (Sandbox Code Playgroud)

e.J*_*mes 5

从该代码片段来看,看起来你有一个"拥有"十个球的控制器,并且你希望球根据一组每个球独有的规则反弹.更面向对象的方法如下:

@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
Run Code Online (Sandbox Code Playgroud)

此设置允许您通过设置其上限和下限来配置所有球一次:

[jumpBall1 setUpperLimit:CGPointMake(60, 211)];
[jumpBall1 setLowerLimit:CGPointMake(0, 82)];
...
Run Code Online (Sandbox Code Playgroud)

然后只需update在你的计时器方法中调用每个球:

- (void) jumpOnTimer {          

    [jumpBall1 update];          
    [jumpBall2 update];
    ...
}
Run Code Online (Sandbox Code Playgroud)

您可以通过将所有球存储在以下内容中进一步简化NSArray:

NSArray * balls = [NSArray arrayWithObjects:jumpBall1, jumpBall2, ..., nil];
Run Code Online (Sandbox Code Playgroud)

然后打电话 makeObjectsPerformSelector:

[balls makeObjectsPerformSelector:@selector(update)];
Run Code Online (Sandbox Code Playgroud)