SpriteKit纹理根据精灵x轴方向变化

时间:2014-11-21 19:08:30

标签: objective-c ios8 sprite-kit sktexture

这似乎是一个需要解决的简单问题,但我不能。正如标题所暗示的那样,我需要将精灵转换为不同的纹理,具体取决于它的走向 - 左或右。这是我尝试做的事情:

if (self.sprite.position.x > 0) //also tried "self.sprite.position.x" instead of 0.
{
    [self.sprite setTexture:[SKTexture textureWithImageNamed:@"X"]];
}
if (self.sprite.position.x < 0)
{
    [self.sprite setTexture:[SKTexture textureWithImageNamed:@"XX"]];
}

两者都没有效用(除非精灵的x轴== 0 -_-)。

我读过这个:SpriteKit: Change texture based on direction 它没有帮助。

编辑: 对不起,我忘了提到精灵的运动在2D空间中是完全随机的。我使用arc4random()。当它上升或下降时,我不需要任何纹理变化。但是左和右对是必不可少的。

我一定是写错了:

if (self.sprite.physicsBody.velocity.dx > 0)
if (self.sprite.physicsBody.velocity.dx < 0)

不适合我。

if (self.sprite.physicsBody.velocity.dx > 5)
if (self.sprite.physicsBody.velocity.dx < -5)

再次明确这个精灵的动作:它是在

的帮助下随机移动的
-(void)update:(CFTimeInterval)currentTime

方法。这是这样实现的:

-(void)update:(CFTimeInterval)currentTime
{
    /* Called before each frame is rendered */

    if (!spritehMoving)
    {   
        CGFloat fX = [self getRandomNumberBetweenMin:-5 andMax:5];
        CGFloat fY = [self getRandomNumberBetweenMin:-5 andMax:7];


        int waitDuration = arc4random() %3;

        SKAction *moveXTo       = [SKAction moveBy:CGVectorMake(fX, fY) duration:1.0];
        SKAction *wait          = [SKAction waitForDuration:waitDuration];
        SKAction *sequence      = [SKAction sequence:@[moveXTo, wait]];
        [self.sprite runAction:sequence];
    }

}

1 个答案:

答案 0 :(得分:1)

您可以检查fX是大于还是小于0,这意味着x轴上的“力”是正(右移)或负(左移)。

这是一个修改过的代码,应该可以解决问题 顺便说一下 - 我还在运动的开始和结束处设置了SpritehMoving BOOL,否则,即使精灵正在移动(这没有任何问题),也会调用此方法,但似乎超出了检查BOOL值的目的。

if (!spritehMoving)
{   
    spritehMoving = YES;  

    CGFloat fX = [self getRandomNumberBetweenMin:-5 andMax:5];
    CGFloat fY = [self getRandomNumberBetweenMin:-5 andMax:7];


    int waitDuration = arc4random() %3;  

    SKAction *changeTexture;  

    if(fX > 0) { // Sprite will move to the right  
        changeTexture = [SKAction setTexture:[SKTexture textureWithImageNamed:@"RightTexture.png"]];  
    } else if (fX < 0) { // Sprite will move to the left  
        changeTexture = [SKAction setTexture:[SKTexture textureWithImageNamed:@"LeftTexture.png"]];  
    } else {  
        // Here I'm creating an action that doesn't do anything, so in case  
        // fX == 0 the texture won't change direction, and the app won't crash    
        // because of nil action  
        changeTexture = [SKAction runBlock:(dispatch_block_t)^(){}];
    }

    SKAction *moveXTo    = [SKAction moveBy:CGVectorMake(fX, fY) duration:1.0];
    SKAction *wait       = [SKAction waitForDuration:waitDuration];  
    SKAction *completion = [SKAction runBlock:(dispatch_block_t)^(){ SpritehMoving = NO; }];
    SKAction *sequence   = [SKAction sequence:@[changeTexture, moveXTo, wait, completion]];
    [self.sprite runAction:sequence];
}