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



这似乎是一个简单的问题,但我不能。正如标题所暗示的那样,我需要我的精灵根据它的方向更改为不同的纹理 - 左或右。这是我尝试做的:

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 -_-)。

我读过这个: 精灵套件:根据方向改变纹理它没有帮助。

编辑:对不起,我忘了提到精灵的移动在 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];
    }

}

您可以检查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];
}

最新更新