2012-07-27 45 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