我正在尝试在box2d环境中设置网格以进行路径查找。这是我的绘图方法,这就是为什么它们之间没有节点和链接被绘制的原因?这是我绘制世界的主要课程:
@interface HelloWorldLayer()
@end
@implementation HelloWorldLayer
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
HelloWorldLayer *layer = [HelloWorldLayer node];
// add layer as a child to scene
[scene addChild: layer];
// return the scene
return scene;
}
-(id) init
{
if( (self=[super init]))
{
[self createGrid];
[self drawGrid];
}
return self;
}
-(void) dealloc
{
[super dealloc];
}
-(void) createGrid
{
//Create 2D array (grid)
nodeSpace = 50.0f;
gridSizeX = 500;
gridSizeY = 500;
grid = [[NSMutableArray alloc] initWithCapacity:(gridSizeX)];
for(int x=0; x<gridSizeX; x++){
[grid addObject:[[NSMutableArray alloc] initWithCapacity:(gridSizeY)]];
}
//Create AStar nodes
for(int x=0; x<gridSizeX; x++){
for(int y=0; y<gridSizeY; y++){
//Add a node
AStarNode *node = [[AStarNode alloc] init];
node.position = ccp(x*nodeSpace + nodeSpace/2, y*nodeSpace + nodeSpace/2);
[[grid objectAtIndex:x] addObject:node];
}
}
//Add neighbors
for(int x=0; x<gridSizeX; x++){
for(int y=0; y<gridSizeY; y++){
//Add a node
AStarNode *node = [[grid objectAtIndex:x] objectAtIndex:y];
//Add self as neighbor to neighboring nodes
[self addNeighbor:node toGridNodeX:x-1 Y:y-1]; //Top-Left
[self addNeighbor:node toGridNodeX:x-1 Y:y]; //Left
[self addNeighbor:node toGridNodeX:x-1 Y:y+1]; //Bottom-Left
[self addNeighbor:node toGridNodeX:x Y:y-1]; //Top
[self addNeighbor:node toGridNodeX:x Y:y+1]; //Bottom
[self addNeighbor:node toGridNodeX:x+1 Y:y-1]; //Top-Right
[self addNeighbor:node toGridNodeX:x+1 Y:y]; //Right
[self addNeighbor:node toGridNodeX:x+1 Y:y+1]; //Bottom-Right
}
}
}
/* Add neighbor helper method */
-(void) addNeighbor:(AStarNode*)node toGridNodeX:(int)x Y:(int)y {
if(x >= 0 && y >= 0 && x < gridSizeX && y < gridSizeY){
AStarNode *neighbor = [[grid objectAtIndex:x] objectAtIndex:y];
if(![AStarNode isNode:neighbor inList:node.neighbors]){
[node.neighbors addObject:neighbor];
}
}
}
-(void) drawGrid
{
for(int x=0; x<gridSizeX; x++){
for(int y=0; y<gridSizeY; y++){
//Draw node
AStarNode *node = [[grid objectAtIndex:x] objectAtIndex:y];
ccDrawColor4F(16, 16, 16, 8);
ccDrawPoint(node.position);
//Draw neighbor lines (there is going to be a lot of them)
for(int i=0; i<node.neighbors.count; i++){
AStarNode *neighbor = [node.neighbors objectAtIndex:i];
ccDrawColor4F(16, 16, 16, 8);
ccDrawLine(node.position, neighbor.position);
}
}
}
}
@end
答案 0 :(得分:2)
您只能在绘图或访问方法中使用OpenGL绘图。
答案 1 :(得分:1)
我认为绘图在init中不起作用。尝试将其放入onEnter
-(void) onEnter {
// at this point, the node has been added, is running
// and will be visited as appropriate (i think)
[super onEnter]; // dont forget to super any 'onMethod' override of cocos2d
[self drawGrid];
}