【发布时间】:2010-10-29 00:25:22
【问题描述】:
我正在尝试编写一个 iPhone 游戏。此功能旨在将重力施加到多个物体上。我从 Python 移植它,我想知道我将字典和数组用作元组是否有意义,并且在 Objective C 中是典型/惯用的。代码中的任何 cmets 都表示赞赏。
+ (void)updateBodies:(NSMutableArray*)bodies {
NSMutableDictionary* totals = [NSMutableDictionary dictionaryWithCapacity:[bodies count]];
for (Body* body in bodies) {
if (body.fixed) {
continue;
}
float tx;
float ty;
for (Body* other in bodies) {
if (other == body) {
continue;
}
float dx = other.x - body.x;
float dy = other.y - body.y;
float dist2 = pow(dx, 2) + pow(dy, 2);
float dist = sqrt(dist2);
float mass = pow(other.radius, 3);
float magnitude = G * mass / dist2;
float ux = dx / dist;
float uy = dy / dist;
tx += ux * magnitude;
ty += uy * magnitude;
}
NSNumber* ntx = [NSNumber numberWithFloat:tx];
NSNumber* nty = [NSNumber numberWithFloat:ty];
NSArray* tuple = [NSArray arrayWithObjects:ntx, nty, nil];
[totals setObject:tuple forKey:body];
}
for (Body* body in [totals allKeys]) {
NSArray* tuple = [totals objectForKey:body];
float tx = [[tuple objectAtIndex:0] floatValue];
float ty = [[tuple objectAtIndex:1] floatValue];
body.dx += tx;
body.dy += ty;
}
}
【问题讨论】:
-
我刚刚意识到我可以在第一个循环中更新
dx和dy。出于某种原因,我认为我必须延迟更新它们,如果我更新x和y,这将是正确的。所以现在这会变得更简单,但它仍然是 NS 集合的好习惯。 -
for (Body* body in [totals allKeys])可以写成for (Body* body in totals)