Вызовы и объявления методов в target-c для cocos2d-iphone

Я абсолютный новичок в c, c и openGL. Поэтому, когда я нашел coco2d, я был очень благодарен за то, что для меня сделали много вещей. Несмотря ни на что, у меня все еще есть проблемы.

После того, как мне удалось заставить анимированный спрайт двигаться на основе прикосновений, я решил немного почистить свой код, добавив метод updateLogic, а затем метод updateDrawing внутри моего таймера, вместо того, чтобы делать все это безобразно внутри таймера. Пока что я собрал этого монстра Франкенштейна, который не компилируется:

GameScene.h

#import <UIKit/UIKit.h>
#import "cocos2d.h"
#import "TestSprite.h"


@interface GameScene : Scene 
{

}


@end

@interface GameLayer : Layer 
{
    //Related to TestSprite
    TestSprite *testSprite;
    int pointX;
    int pointY;
    bool goingUp;
    int TestSpriteSpeed;
}
//Functions
-(void) updateLogic;
-(void) updateDrawings;
-(void) moveTestSprite;

@property (nonatomic, retain) TestSprite *testSprite;


@end

GameScene.m

#import "GameScene.h"
#import "MenuScene.h"

@implementation GameScene
- (id) init {
    self = [super init];
    if (self != nil) {
        //Background management and stuff to go here
        [self addChild:[GameLayer node] z:1];
    }
    return self;
}
@end

@implementation GameLayer

@synthesize testSprite;

- (void) dealloc
{
    [testSprite release];
    [super dealloc];
}

-(id) init
{
    self = [super init];

    if (self)
    {
        isTouchEnabled = YES;

        //Create our test sprite
        TestSprite *sprite = [[TestSprite alloc] init];
        self.testSprite = sprite;
        [sprite release];

        //Add the test sprite to the Scene
        [self add:testSprite];
        [testSprite setPosition:cpv(0,0)];

        //Schedule a timer
        [self schedule: @selector(timer:) interval:0.01];


    }
    return self;
}

-(void) moveTestSprite
{
    //Reached optimal y?
    if ([testSprite position].x - pointX == 0) {goingUp = TRUE;}
    if ([testSprite position].y - pointY == 0) {goingUp = FALSE;}
    if (goingUp)
    {
        if (pointY > [testSprite position].y)
        {
            testSprite.position = cpv([testSprite position].x,[testSprite position].y+1);
        }
        if (pointY < [testSprite position].y)
        {
            testSprite.position = cpv([testSprite position].x,[testSprite position].y-1);
        }
    }
    else
    {
        if ([testSprite position].x > pointX)
        {
            testSprite.position = cpv([testSprite position].x-1,[testSprite position].y);
        }
        if ([testSprite position].x < pointX)
        {
            testSprite.position = cpv([testSprite position].x+1,[testSprite position].y);
        }
    }
}   

-(void) updateLogic 
{
}

-(void) updateDrawings
{
    moveTestSprite();
}



-(void) timer: (ccTime) dt
{
    updateLogic();
    updateDrawings();
}

- (BOOL) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *) event
{
    UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView: [touch view]];
    /* two ugly hacks here. First in pointX: for some reason the point coords and sprite coords were reversed so the number was flipped
    secound: factored in the size of sprite 44x64 to have the sprite's center end on the clicked spot. a size property would be better*/
    pointY = abs(point.y-480)-32;
    pointX = point.x-22;
    //Finds if the difrence between the two points on the y is greater than on the x and than decides which was to go first
    if (abs([testSprite position].x - pointX) < abs([testSprite position].y - pointY)) {goingUp = TRUE;}
    return YES;
}

@end

Судя по моему коду, я явно не самый лучший программист. Журнал ошибок:

Undefined symbols:
  "_updateLogic", referenced from:
      -[GameLayer timer:] in GameScene.o
  "_updateDrawings", referenced from:
      -[GameLayer timer:] in GameScene.o
  "_moveTestSprite", referenced from:
      -[GameLayer updateDrawings] in GameScene.o

person deeb    schedule 29.06.2009    source источник


Ответы (2)


Вызовите свои функции updateXXX следующим образом:

[self updateLogic];
[self updateDrawings];

Поскольку вы вызываете их так: updateLogic(), компоновщик ищет реализацию функции в стиле C при связывании вашего исполняемого файла вместе и не находит ее.

person drewh    schedule 29.06.2009

Вы получили ответ от Drawh для вашей текущей проблемы, но включение предупреждений (предупреждающие флаги "-Wall") сообщило бы вам о проблеме во время компиляции, а не во время компоновки, жалуясь на то, что updateLogic() не определен.

person Peter N Lewis    schedule 30.06.2009