在Cocos2d中更改对象的状态

时间:2013-10-31 14:48:34

标签: cocos2d-iphone

首先,我想为一个完整的新手道歉,但我已经研究过网络,无法找到解决当前问题的方法。 我有3个对象(精灵),我已经使用switch语句单独设置,并希望使用我的主游戏区域将其状态随机更改为我已经在对象单独的标题和实现文件中定义的动画。 我已经设置了一个自我调度updater和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

1 个答案:

答案 0 :(得分:0)

最后发现我需要的只是将以下代码添加到我的TBT gameCharacters-(void)updateStateWithDeltaTime:method ...

if(characterState == kStateTest){

    if (characterState != kStateTest) {
        [self changeState:kStateTest];
        return;
    }

现在它运作正常。

再次感谢Mikael试图帮助我。