gpt4 book ai didi

iphone 代码 - CGPoint 问题

转载 作者:搜寻专家 更新时间:2023-10-30 19:54:39 25 4
gpt4 key购买 nike

我有 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...

最佳答案

从该代码片段来看,您似乎有一个“拥有”十个球的 Controller ,并且您希望这些球根据一组每个球独有的规则来回弹跳。更面向对象的方法如下:

@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)];

关于iphone 代码 - CGPoint 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1986129/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com