就上下文而言,我正在iOS中制作破砖游戏,并希望我创建的砖块在球体反弹时反复向左和向右移动。
我的代码中有一个方法,我在场景出现时调用一次方法,将几行精灵节点作为砖块添加到场景中,如下所示
-(void) addBricks:(CGSize)size {
// add a new row of bricks
for (int j = 1; j <= 3; j++) {
// add top column of bricks
for (int i = 0; i < 5; i++) {
SKSpriteNode *brick = [SKSpriteNode spriteNodeWithImageNamed:@"brick"];
brick.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:brick.frame.size];
brick.physicsBody.dynamic = NO;
brick.physicsBody.categoryBitMask = brickCategory;
int xPos = ((brick.frame.size.width / 2) + 20) + ((brick.frame.size.width / 2) + 30) * i;
int yPos = size.height - (30 * j);
// generate the sequence that the brick will perform
SKAction *moveHorizontal = [SKAction moveToX:xPos + 20 duration:1.0f];
moveHorizontal.timingMode = SKActionTimingEaseOut;
SKAction *moveBack = [moveHorizontal reversedAction];
SKAction *wait = [SKAction waitForDuration:0.4f];
SKAction *backAndForth = [SKAction sequence:@[moveHorizontal, wait, moveBack, wait]];
SKAction *repeatHorizMove = [SKAction repeatActionForever:backAndForth];
brick.position = CGPointMake(xPos, yPos);
// add the brick
[self addChild:brick];
// make it move back and forth
[brick runAction:repeatHorizMove];
}
}
}
我的问题是,虽然所有的砖块都会在场景开始时向右移动,但它们不会向后移动并像我希望的那样反复重复动作。我认为在以编程方式创建它们时可能与它们具有相同的名称有关,但我知道尽管它们具有相同的名称,但场景仍保留所有砖块。
我如何才能获得它,以便我创建的所有SpriteNodes(砖块)永远来回移动?
答案 0 :(得分:2)
moveToX action不可逆转。请务必查看参考文献以获取此类评论。
这应该解决它:
SKAction *moveHorizontal = [SKAction moveToX:xPos + 20 duration:1.0f];
moveHorizontal.timingMode = SKActionTimingEaseOut;
SKAction *moveBack = [SKAction moveToX:xPos duration:1.0];