0

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

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:根据方向改变纹理 它没有帮助。

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

}

4

1 回答 1

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];
}
于 2014-11-22T13:04:18.177 回答