iphone代码 - CGPoint问题

时间:2009-12-31 16:51:20

标签: 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...

3 个答案:

答案 0 :(得分: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

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

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

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

- (void) jumpOnTimer {          

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

您可以通过将所有球存储在NSArray

中来进一步简化此操作
NSArray * balls = [NSArray arrayWithObjects:jumpBall1, jumpBall2, ..., nil];

然后拨打makeObjectsPerformSelector:

[balls makeObjectsPerformSelector:@selector(update)];

答案 1 :(得分:3)

你可以创建一个jumpBalls数组,然后循环遍历每个并执行代码。你可以这样做:

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;
}

答案 2 :(得分:2)

看起来你正在尝试手动制作动画。请查看使用UIView animations而不是