2012-07-27 50 views
1

我有几张地图(使用Tiled QT制作的地图),我想根据这些地图的对象组(我叫它Waypoints)创建一个CGpoint **数组。如何创建一个动态CGPoint **数组

每个地图都可以有一些我称之为路径的航点。

//Create the first dimension 
int nbrOfPaths = [[self.tileMap objectGroups] count]; 
CGPoint **pathArray = malloc(nbrOfPaths * sizeof(CGPoint *)); 

那么对于第二个维度

//Create the second dimension 
int pathCounter = 0; 
while ((path = [self.tileMap objectGroupNamed:[NSString stringWithFormat:@"Path%d", pathCounter]])) { 
    int nbrOfWpts = 0; 
    while ((waypoint = [path objectNamed:[NSString stringWithFormat:@"Wpt%d", nbrOfWpts]])) { 
     nbrOfWpts++; 
    } 
    pathArray[pathCounter] = malloc(nbrOfWpts * sizeof(CGPoint)); 
    pathCounter++; 
} 

现在我要填补pathArray

//Fill the array 
pathCounter = 0; 
while ((path = [self.tileMap objectGroupNamed:[NSString stringWithFormat:@"Path%d", pathCounter]])) 
{ 
    int waypointCounter = 0; 
    //Get all the waypoints from the path 
    while ((waypoint = [path objectNamed:[NSString stringWithFormat:@"Wpt%d", waypointCounter]])) 
    { 
     pathArray[pathCounter][waypointCounter].x = [[waypoint valueForKey:@"x"] intValue]; 
     pathArray[pathCounter][waypointCounter].y = [[waypoint valueForKey:@"y"] intValue]; 
     NSLog(@"x : %f & y : %f",pathArray[pathCounter][waypointCounter].x,pathArray[pathCounter][waypointCounter].y); 
     waypointCounter++; 
    } 

    pathCounter++; 
} 

当我的NSLog(@ “%@”,pathArray),它为我整个路径阵列将x和y。

无论其2问题

  • y值是永远正确的(x的值是正确的,我tilemap.tmx是正确的太)

    <object name="Wpt0" x="-18" y="304"/> <-- I get x : -18 and y :336 with NSLog 
    <object name="Wpt1" x="111" y="304"/> <-- I get x : 111 and y :336 
    <object name="Wpt2" x="112" y="207"/> <-- I get x : 112 and y :433 
    
  • 我得到一个EX_BAD_ACCESS在NSLog末尾

编辑 谢谢关于CGPoint的NSLog(%@)。 不过,我得到这条线(在丑陋的循环)的y值:

所有的
NSLog(@"x : %f & y : %f",pathArray[pathCounter][waypointCounter].x,pathArray[pathCounter][waypointCounter].y); 
+1

你的代码看起来不错,你可以显示到'NSLog'的确切调用吗?你不打算用'%@'说明符打印'pathArray',对吗?因为该说明符是用于对象的,而'pathArray'是一个C数组。您需要使用与填充它相同的两个嵌套循环排列来完成它。 – dasblinkenlight 2012-07-27 10:14:31

回答

1

首先,你不能的NSLog CGPoint一样,因为它不是一个对象。 %@需要一个客观的c对象来发送一个description消息。其次,您可以使用NSValue包装,然后像使用任何其他对象一样使用NSMutableArray。有没有你不想这样做的理由?你可以像你一样在其他数组内添加数组。

+0

我删除了NSLog(%@),没有EXC_BAD_ACCESS,但仍然存在这个y值问题。实际上,关于NSValue:我来自C++,仍然不明白带有addObject和东西的NSMutableArray是如何工作的。如果你可以给我一些很好的干净的例子2d/3d数组=)谢谢! – Kalzem 2012-07-27 10:24:01

+1

在obj-c中的NSMutableArray像C++中的一个向量一样工作,除了代替push_back,你使用addObject而不是pop来使用removeObject/removeObjectAtIndex,removeLastObject等。 – borrrden 2012-07-27 10:30:35

+0

好吧,我试图在Obj-C中而不是普通的C 。这是我得到:http://stackoverflow.com/questions/11698682/how-to-dynamically-create-a-2d-nsmutablearray-with-loops – Kalzem 2012-07-28 05:57:15

1

关于第一个问题:

y值是永远正确的(x的值是正确的,我tilemap.tmx是太正确)

你是否注意到,如果你加入从瓦片地图和NSLog的y值,他们总是加起来640?然后,您最好检查一下tilemap y坐标是否从顶到底与CGPoint的底部到顶部相反。然后你总是可以做640-y转换两个坐标系之间的y坐标。

+0

哇!太好了!其实y是从tilemap.tmx正确读取的。这只是NSLog会变成nut =)所以如果我在代码的其余部分中不使用任何对象(如在x/y坐标上添加一个精灵),就不应该有任何问题, – Kalzem 2012-07-27 17:43:59