在 sprite.runAction 之后调用 Block 时崩溃



我在使用目标 C 时遇到问题。我试图在移动精灵后调用一个块

我想要实现的简短版本是,我想移动阵列中的所有敌人,当每个敌人完成移动时,我想检查它是否发生了碰撞。

下面的简化代码显示了我正在尝试做的事情。

我的 Actor 类是这样定义的

// -----------------------------
// Actor.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "ScreenObject.h"
typedef void (^actorMoveComplete)(void);
@interface Actor : ScreenObject
{
   // actorMoveComplete onMoveComplete;
}
@property (nonatomic) BOOL isMoving;
@property (readwrite, copy) actorMoveComplete onMoveComplete;
@property (nonatomic, retain) CCSprite* sprite;
-(void) moveTo:(CGPoint)targetPosition Speed:(float) speed withCallback:(actorMoveComplete)moveComplete;
@end
// -----------------------------
//  Actor.m
#import "Actor.h"
@implementation Actor
@synthesize onMoveComplete;
@synthesize sprite;
-(void) moveTo:(CGPoint)targetPosition Speed:(float) speed withCallback:(actorMoveComplete)moveComplete;
{
    onMoveComplete = moveComplete;
    id actionMove = [CCMoveTo actionWithDuration:speed position:targetPosition];
    id actionMoveDone = [CCCallFuncN actionWithTarget:self selector:@selector(spriteMoveFinished:)];
    [super.sprite runAction:[CCSequence actions:actionMove, actionMoveDone, nil]];
}
-(void) spriteMoveFinished:(id) sender
{
    isMoving = NO;
    if (onMoveComplete != nil)
        onMoveComplete();
}
@end

如您所见,我正在尝试将块存储在onMoveComplete参数中(我也在私有变量中尝试过(,然后在精灵移动完成后调用它。

在我的调用类中,我正在遍历一堆参与者(敌人(,我想在移动完成后为每个参与者调用这个匿名代码块:

{
   [self checkForCollision:enemy];
}

我的调用类看起来像这样。

//------------------------------
//
//  GameLayer.h
#import "cocos2d.h"
#import "Actor.h"
@interface GameLayer : CCLayerColor
{
}
@property (nonatomic, copy) NSMutableArray *enemies;
- (void) updateEnemies;
- (void) checkForCollision:(Actor*)actor;
- (BOOL) isMapGridClear:(CGPoint)mapGrid excludeActor:(Actor*)actor;
@end

//------------------------------
//  GameLayer.m
#import "GameLayer.h"

@implementation GameLayer
@synthesize enemies;
- (void) updateEnemies
{
    for (Actor *enemy in enemies)
    {
        //  
        CGPoint newPosition = [self getNewPosition:enemy]; /* method to figure out new position */
        [enemy moveDelta:ccp(dX, dY) Speed:enemySpeed withCallback:^{
            [self checkForCollision:enemy];
        }];
    }
}

- (void) checkForCollision:(Actor*)actor
{
    if (![self isMapGridClear:actor.gridPosition excludeActor:actor])
    {
        actor.isCrashed=YES;
        [actor loadSprite:self spriteImage:@"crashed.png"];
    }
}

- (BOOL) isMapGridClear:(CGPoint)mapGrid excludeActor:(Actor*)actor
{
    /* Actual method figures out if there was a collision    */
    return YES;
}
@end

不幸的是,当我调用onMoveComplete块时,我不断收到EXC_BAD_ACCESS错误有趣的是,如果我尝试在 moveTo 方法中调用块,它可以工作(但当然我希望它在移动完成后触发(。

谁能帮助我做错什么。 我什至使用了正确的机制吗?

(对于格式不佳、不完整的代码段表示歉意(

您正确地将属性声明为 copy,但您将实例变量直接设置为块的地址,而无需使用生成的访问器。这意味着该块不会被复制并在调用之前被销毁。

使用self.onMoveCompleted = moveCompleted分配您的块,您会没事的。

最新更新