【发布时间】:2009-12-22 06:04:35
【问题描述】:
总的来说,我是 Objective-C 和 iPhone 开发的新手。我正在使用 Cocos2d-iphone 库作为游戏引擎,试图开发一个非常简单的游戏。
我一直在学习一些教程来掌握事情的窍门,并试图建立一个非常简单的“关卡”,其中一些球使用 Chipmunk 物理引擎在屏幕上弹跳。下面是导致问题的文件的定义和实现。编译时产生的警告是:
GameScene.m:69:警告:“GameLayer”可能不会响应“-addChild:z:”
GDB 还提供以下功能:
由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“*** -[GameLayer addChild:z:]:无法识别的选择器已发送到实例 0xf6ff90”
如果我注释掉这一行,则在调用 GameLayer 时程序将不再崩溃。 (用“
// GameScene.h
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "chipmunk.h"
@interface GameScene : Scene
{
}
@end
@interface GameLayer : Layer
{
cpSpace *space;
}
-(void) makeBall: (float) x y:(float)y;
-(void) setupGame;
@end
然后是实现:
// GameScene.m
#import "MenuScene.h"
#import "GameScene.h"
void updateShape(void* ptr, void* unused){
cpShape* shape = (cpShape*)ptr;
Sprite* sprite = shape->data;
if(sprite){
cpBody* body = shape->body;
[sprite setPosition:cpv(body->p.x, body->p.y)];
}
}
@implementation GameScene
- (id) init {
self = [super init];
if (self != nil) {
Sprite * bg = [Sprite spriteWithFile:@"background.png"];
[bg setPosition:cpv(240, 160)];
[self add:bg z:0];
[self add:[GameLayer node] z:1];
}
return self;
}
@end
@implementation GameLayer
- (id) init {
self = [super init];
if(self != nil) {
isTouchEnabled = YES;
}
//Make it shoot:
isTouchEnabled = YES;
//Initialize Chipmunk:
cpInitChipmunk();
// Create the chipmunk space
space = cpSpaceNew();
cpSpaceResizeStaticHash(space, 400.0f, 40);
cpSpaceResizeActiveHash(space, 100, 600);
space->gravity = cpv(0, -400);
space->elasticIterations = space->iterations;
// Update Chipmunk
// Calls the "tick" function below. This function subsequently
// makes a call to the update function which updates all of the
// sprites on the screen.
[self schedule: @selector(tick:) interval: 1.0f/60.0f];
// Setup the game (place the player and balls on the screen)
[self makeBall:100 y:100];
return self;
}
// Sets up the game, placing the balls on the stage. Also creates the
// flor boundries and player
-(void) setupGame {
}
// Creates a ball and adds it to the desired location on the screen
-(void) makeBall: (float) x y:(float)y {
Sprite *ball = [[Sprite spriteWithFile:@"start_ball.png"] retain];
ball.position = cpv(x,y);
[self addChild:ball z:2]; << Apparently this line is causing the error?
}
-(void)tick: (ccTime)dt {
cpSpaceStep(space, 1.0f/60.0f);
//cpSpaceHashEach(space->activeShapes, &updateShape, nil);
}
@end
我已经在上面的代码中注释了我认为导致错误的行。 (
我确定这很愚蠢,但我们将不胜感激!
谢谢:)
【问题讨论】:
标签: iphone objective-c cocos2d-iphone