Cocos2d iphone 更改Cocos2d中对象的状态

Cocos2d iphone 更改Cocos2d中对象的状态,cocos2d-iphone,Cocos2d Iphone,首先,我想为自己是一个完全的新手而道歉,但我已经研究过网络,无法找到解决当前问题的方法。 我用switch语句单独设置了3个对象精灵,希望使用我的主游戏层将它们的状态随机更改为一个动画,我已经在对象单独的头文件和实现文件中定义了该动画。 我已经设置了一个self-schedule更新程序和arc4random方法,它可以工作,但不会更改对象的状态,因为它只调用我也包含在语句中的CCLOG 我已经列出了下面的代码,我知道这有点混乱,但我仍然是初学者的第一步,如果有人能给我指出正确的方向,那就是如果

首先,我想为自己是一个完全的新手而道歉,但我已经研究过网络,无法找到解决当前问题的方法。 我用switch语句单独设置了3个对象精灵,希望使用我的主游戏层将它们的状态随机更改为一个动画,我已经在对象单独的头文件和实现文件中定义了该动画。 我已经设置了一个self-schedule更新程序和arc4random方法,它可以工作,但不会更改对象的状态,因为它只调用我也包含在语句中的CCLOG

我已经列出了下面的代码,我知道这有点混乱,但我仍然是初学者的第一步,如果有人能给我指出正确的方向,那就是如果我以你能理解的方式解释了这一点!我将非常感激

提前感谢您查看此问题

    //-------------------below is my gameplaylayer header file---------//

//  GamePlayLayer.h

#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "CCLayer.h"
#import "SneakyJoystick.h"
#import "SneakyButton.h"
#import "SneakyButtonSkinnedBase.h"
#import "SneakyJoystickSkinnedBase.h"
#import "Constants.h"
#import "CommonProtocols.h"
#import "TBT.h"
#import "MBT.h"
#import "BBT.h"
#import "BC.h"
#import "GameCharacter.h"
#import <stdlib.h>

@interface GamePlayLayer : CCLayer <GamePlayLayerDelegate> {
    CCSprite *vikingSprite;

    SneakyJoystick *leftJoystick;
    SneakyButton *jumpButton;
    SneakyButton *attackButton;
    CCSpriteBatchNode *sceneSpriteBatchNode;

}
@property (readwrite) CharacterStates characterState;


-(void)changeState:(CharacterStates)newState;
-(void)addEnemy;
@end

//---------------------Below is my gameplaylayer implementation file-------------//

//  GamePlayLayer.m

#import "GamePlayLayer.h"

@implementation GamePlayLayer
@synthesize characterState;


-(void) dealloc {
    [leftJoystick release];
    [jumpButton release];
    [attackButton release];
    [super dealloc];
    }

-(void)initJoystickAndButtons {
    CGSize screenSize = [CCDirector sharedDirector].winSize;

//---DELETED MOST OF THE ABOVE METHOD AS NOT NEEDED FOR THIS QUESTION----//

-(void) update:(ccTime)deltaTime {
    CCArray *listOfGameObjects =
    [sceneSpriteBatchNode children];                     
    for (GameCharacter *tempChar in listOfGameObjects) {         
        [tempChar updateStateWithDeltaTime:deltaTime andListOfGameObjects:listOfGameObjects];                         
    }
}
-(void) createObjectOfType: (GameObjectType)objectType
                withHealth:(int)initialHealth atLocation:(CGPoint)spawnLocation withZValue:(int)ZValue {
    if (objectType == kEnemyType1BT) {
        CCLOG(@"creating the 1BT");
        TBT *tBT = [[TBT alloc] initWithSpriteFrameName:@"BT_anim_1.png"];
        [tBT setCharacterHealth:initialHealth];
        [tBT setPosition:spawnLocation];
        [sceneSpriteBatchNode addChild:tBT
                                     z:ZValue
                                   tag:k1BTtagValue];
        [tBT release];} 

    if (objectType == kEnemyType3BT){
        CCLOG(@"creating the radar enemy");
        BBT *bBT = [[BBT alloc] initWithSpriteFrameName:@"BT_anim_1.png"];
        [bBT setCharacterHealth:initialHealth];
        [bBT setPosition:spawnLocation];
        [sceneSpriteBatchNode addChild:bBT
                                     z:ZValue
                                   tag:k3BTtagValue];
        [bBT release];
    }

    if (objectType == kEnemyType2BT){
        CCLOG(@"creating the radar enemy");
        MBT *mBT = [[MBT alloc] initWithSpriteFrameName:@"BT_anim_1.png"];
        [mBT setCharacterHealth:initialHealth];
        [mBT setPosition:spawnLocation];
        [sceneSpriteBatchNode addChild:mBT
                                     z:ZValue
                                   tag:k2BTtagValue];
        [mBT release];
    }
}

//--PROBLEM I HAVE IS BELOW--//

-(void)addEnemy {
    int x =  (arc4random() % 3);
    TBT *tBT = (TBT*)
    [sceneSpriteBatchNode getChildByTag:kEnemyType1BT];

    //--Just using one object(sprite) to begin with--//

    if (x>0) {
        CCLOG(@"RANDOM KSTATETEST!!!!!!");
        [tBT changeState:kStatetest];  <---it is not changing state to kStatetest
      }

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

    if (self !=nil) {

        CGSize screenSize = [CCDirector sharedDirector]. winSize;
self.TouchEnabled = YES;

        srandom(time(NULL));

        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            [[CCSpriteFrameCache sharedSpriteFrameCache]
             addSpriteFramesWithFile:@"scene1atlas.plist"];          // 1
            sceneSpriteBatchNode =
            [CCSpriteBatchNode batchNodeWithFile:@"scene1atlas.png"]; // 2
        } else {
            [[CCSpriteFrameCache sharedSpriteFrameCache]
             addSpriteFramesWithFile:@"scene1atlasiPhone.plist"];          // 1
            sceneSpriteBatchNode =
            [CCSpriteBatchNode batchNodeWithFile:@"scene1atlasiPhone.png"];// 2
        }


        [self addChild:sceneSpriteBatchNode z:0];                // 3
        [self initJoystickAndButtons];                           // 4
        BC *viking = [[BC alloc]
                          initWithSpriteFrame:[[CCSpriteFrameCache
                                                sharedSpriteFrameCache]
                                               spriteFrameByName:@"BCmoving_anim_1.png"]];            
        //[viking setJoystick:leftJoystick];
        [viking setJumpButton:jumpButton];
        [viking setAttackButton:attackButton];
        [viking setPosition:ccp(screenSize.width * 0.19f,
                                screenSize.height * 0.19f)];
        [viking setCharacterHealth:3];

        [sceneSpriteBatchNode
         addChild:viking
         z:kVikingSpriteZValue
         tag:kVikingSpriteTagValue];           heatlh is set to 100

     [self schedule:@selector(addEnemy) interval:1.0f];


        [self createObjectOfType:kEnemyType1BT withHealth:3 atLocation:ccp(screenSize.width * 0.0439f, screenSize.height * 0.822f) withZValue:10];


        [self createObjectOfType:kEnemyType3BT withHealth:3 atLocation:ccp(screenSize.width * 0.0439f, screenSize.height * 0.45f) withZValue:10];

        [self createObjectOfType:kEnemyType2BT withHealth:3 atLocation:ccp(screenSize.width * 0.0439f, screenSize.height * 0.638f) withZValue:10];
               //Sets up the schedular call that will fire the update method in GamePlayLayer.m every frame.
        [self scheduleUpdate];


    }

    return self;

}

@end
//---------下面是我的一个对象头文件-------//

#import <Foundation/Foundation.h>
#import "GameCharacter.h"


@interface TBT : GameCharacter{

    CCAnimation *tiltingAnim;
    CCAnimation *transmittingAnim;
    CCAnimation *loseLifeAnim;
    CCAnimation *throwingAnim;
    CCAnimation *afterThrowingAnim;    
    CCAnimation *shootPhaserAnim;    

    GameCharacter *vikingCharacter;
    id <GamePlayLayerDelegate> delegate;

}
@property (nonatomic,assign) id <GamePlayLayerDelegate> delegate;
@property (nonatomic, retain) CCAnimation *tiltingAnim;
@property (nonatomic, retain) CCAnimation *transmittingAnim;
//@property (nonatomic, retain) CCAnimation *takingAHitAnim;
@property (nonatomic, retain) CCAnimation *loseLifeAnim;
@property (nonatomic, retain) CCAnimation *throwingAnim;
@property (nonatomic,retain) CCAnimation *afterThrowingAnim;
@property (nonatomic,retain) CCAnimation *shootPhaserAnim;

-(void)initAnimations;


@end


//-----------------below is the .m file for one of my objects--------------//

#import "TBT.h"

@implementation TBT

@synthesize delegate;
@synthesize tiltingAnim;
@synthesize transmittingAnim;
@synthesize loseLifeAnim;
@synthesize throwingAnim;
@synthesize afterThrowingAnim;
@synthesize shootPhaserAnim;



-(void) dealloc {
    delegate = nil;

    [tiltingAnim release];
    [transmittingAnim release];
    [loseLifeAnim release];
    [throwingAnim release];
    [afterThrowingAnim release];
    [shootPhaserAnim release];

    [super dealloc];
}


-(void)shootPhaser {
    CGPoint phaserFiringPosition;
    PhaserDirection phaserDir;
    CGRect boundingBox = [self boundingBox];
    CGPoint position = [self position];

    float xPosition = position.x + boundingBox.size.width * 0.542f;
    float yPosition = position.y + boundingBox.size.height * 0.25f;

    if ([self flipX]) {
        CCLOG(@"TBT Facing right, Firing to the right");
        phaserDir = kDirectionRight;
    } else {
        CCLOG(@"TBT Facing left, Firing to the left");
        xPosition = xPosition * -1.0f;
        phaserDir = kDirectionLeft;
    }
    phaserFiringPosition = ccp(xPosition, yPosition);
    [delegate createPhaserWithDirection:phaserDir andPosition:phaserFiringPosition];
}

-(void)changeState:(CharacterStates)newState {
    [self stopAllActions];
    id action = nil;
    [self setCharacterState:newState];

    switch (newState) {
        case kStatespawning:
            CCLOG(@"TBT->Changing State to Spwaning");
            [self setDisplayFrame:
             [[CCSpriteFrameCache sharedSpriteFrameCache]
              spriteFrameByName:@"BT_anim_1.png"]];
            break;


        case kStateIdle:
            CCLOG(@"TBT->schaning state to idle");
            [self setDisplayFrame:
             [[CCSpriteFrameCache sharedSpriteFrameCache]
              spriteFrameByName:@"BT_anim_1.png"]];

            break;

        case kStatetest:
            CCLOG(@"TBT->Changing State to test");
            action = [CCSequence actions : [CCDelayTime actionWithDuration:1.5f],[CCAnimate actionWithAnimation:transmittingAnim], nil];
            break;

        default:
            CCLOG(@"unhandled state %d in TBT", newState);
            break;
    }

    if (action !=nil) {
        [self runAction:action];

    }
}

-(void)updateStateWithDeltaTime: (ccTime)deltaTime andListOfGameObjects:(CCArray*)listOfGameObjects {

    if (characterState == kStateDead)
        return;

    if ((([self numberOfRunningActions] == 0) && (characterState != kStateDead)) ) {
        CCLOG(@"TBT Going to Idle");
        [self changeState:kStateIdle];
        return;
    }

}


-(void)initAnimations {
    [self setTiltingAnim:[self loadPlistForAnimationWithName:@"tiltingAnim" andClassName:NSStringFromClass([self class])]];

    [self setTransmittingAnim:[self loadPlistForAnimationWithName:@"transmittingAnim" andClassName:NSStringFromClass([self class])]];

}

-(id) initWithSpriteFrameName:(NSString*)frameName{
    if ((self=[super init])) {
        if ((self = [super initWithSpriteFrameName:frameName])) {
            CCLOG(@"### TBT initialized");
            [self initAnimations];
            characterHealth = 3.0f;
            gameObjectType = kEnemyType1BT;
            [self changeState:kStatespawning];
        }}
    return self;

}

@end

最后,我发现我所需要的只是将以下代码添加到我的TBT gameCharacters voidupdateStateWithDeltaTime中:方法

如果characterState==kStateTest{

    if (characterState != kStateTest) {
        [self changeState:kStateTest];
        return;
    }
现在它工作得很好


再次感谢Mikael帮助我。

您的对象中是否调用了-voidchangeState:CharacterStatesnewState?您可能应该将-voidchangeState:CharacterStatesnewState;从GamePlayLayer.h类移动到对象的头文件中。您好,Mikael,感谢您的响应。在objects.m文件中调用了characterState方法d然后我想我到底在做什么!将它导入gameplaylayer。我也尝试了你的建议,不幸的是我仍然有同样的问题。我想说我终于发现了问题所在,但我想再次表示感谢Mikael