更改SourceRect以通过精灵表向前和向后计数

时间:2013-10-24 16:58:05

标签: c++ animation 2d sprite

这是我的更新方法,当前循环通过我的6个精灵为行走角色,它计数0,1,2,3,4,5然后重置为0。

任务是让它向前循环然后向后循环0,1,2,3,4,5,4,3,2,1,0,1,2 ......等等。

我试图在某些条件下实现几种计数方法来计数和倒计时,但它们似乎在第4/5帧之间进行对抗和循环。

有快速解决方案吗?或者任何人都可以指出我的方向解决方案请:)

    void SpriteGame::Update(int tickTotal, int tickDelta){

    if ( tickTotal >= this->playerLastFrameChange + (TICKS_PER_SECOND / playerSheetLength) )
    {
        this->playerFrame = this->playerFrame + 1;
        this->playerLastFrameChange = tickTotal;

        if (this->playerFrame >= this->playerSheetLength)
        {
            this->playerFrame = 0;
        }

        this->playerSourceRect->left = this->playerFrame * widthOfSprite;
        this->playerSourceRect->top = 0;
        this->playerSourceRect->right = (this->playerFrame + 1) * widthOfSprite;
        this->playerSourceRect->bottom = widthOfSprite;
    }
}

实现(abs())方法工作计数0,1,2,3,4,5,4,3,2,1,2 ..等

//initializing playerFrame = -4; at the top of the .cpp

this->playerFrame = this->playerFrame +1; //keep counting for as long as its <= 5 [sheet length]

if (this->playerFrame >= this->playerSheetLength)
{
this->playerFrame = -4;
}

this->playerSourceRect->left = (abs(playerFrame)) * widthOfSprite;
this->playerSourceRect->top = 0;
this->playerSourceRect->right = (abs(playerFrame)+1) *     widthOfSprite;
this->playerSourceRect->bottom = widthOfSprite

3 个答案:

答案 0 :(得分:0)

怎么样这样:

char direction=1; //initialize forward

this->playerFrame+=direction;
if(this->playerFrame >= this->playerSheetLength || this->playerFrame <=0)
  direction*=-1;

答案 1 :(得分:0)

要坚持你开始使用的算术方法,你需要像这样的伪代码

if( /*it's time to update frame*/ )
{
    if( currentFrame >= maxFrame || 
        currentFrame <= minFrame   )
    {
        incrementer *= -1;
    }

    currentFrame += incrementer;
    // Then calculate the next frame boundary based on the frame number

 }

或者如果你在一个向量中保留了一个矩形集合,你可以简单地迭代结束,然后反向迭代到开头,依此类推。

Google std::vector, std::vector::begin(), std::vector::end(), std::vector::rbegin(), std::vector::rend()

快速举例:

vector<rect> vec;
.
.
.
for(vector<rect>::iterator iter = vec.begin(); iter != vec.end(); ++iter)
{
    ....
}

for(vector<rect>::reverse_iterator iter = vec.rbegin(); iter != vec.rend(); ++iter)
{
    ....
}

答案 2 :(得分:0)

让它连续计数和下降的一种相当简单的方法是将计数从-4运行到5(总是递增)。当它超过5时,将其设置回-4。

要从该计数中获取实际精灵指数,只需取其绝对值(abs())。这将给你正面等价的任何负值,但保持正值不变。