寻找或算法或设计模式的布尔选择

时间:2013-08-28 08:38:06

标签: algorithm design-patterns

我遇到的情况是,如果满足一个条件,即使它们在下一阶段变为真,也必须禁用其他条件。

基本上我每次移动精灵时都会触发一个方法。我想限制移动到单轴,所以当它开始在 x 轴上移动时,它只能在 x 上移动,直到拖动结束。

我正在寻找某种优雅的方式来做到这一点,而不是保持观察4变量状态。

E.g。在伪代码中,我需要完成以下操作(对于 x 轴):

if sprite starts to move along the X axis:
    set state == moveRight
if sprite moves more then 1 pixel on the Y axis and moveRight == true:
    do nothing

这就是我现在所拥有的:

void GameController::handleTouchMoved(CCTouch* touch)
{   
    // right
    if(dragX > dragPrevX)
    {
        pSelectedCurrent->setPosition(ccp(pSelectedCurrent->getPositionX()+movmentSpeed,pSelectedCurrent->getPositionY()));
    }
    // left
    else if(dragX < dragPrevX)
    {
        pSelectedCurrent->setPosition(ccp(pSelectedCurrent->getPositionX()-movmentSpeed,pSelectedCurrent->getPositionY()));
    }
    // up
    else if(dragY > dragPrevY)
    {
        pSelectedCurrent->setPosition(ccp(pSelectedCurrent->getPositionX(),pSelectedCurrent->getPositionY()+movmentSpeed));
    }
    // down 
    else if(dragY < dragPrevY)
    {
        pSelectedCurrent->setPosition(ccp(pSelectedCurrent->getPositionX(),pSelectedCurrent->getPositionY()-movmentSpeed));
    }   
}

2 个答案:

答案 0 :(得分:1)

你可以这样做:

void GameController::handleTouchMoved(CCTouch* touch)
{   
    // right and left
    if(dragX != dragPrevX)
    {
        pSelectedCurrent->setPosition(ccp(pSelectedCurrent->getPositionX()+(dragX-dragPrevX)/(abs(dragX-dragprevX)*movmentSpeed,pSelectedCurrent->getPositionY()));
    }
// up and down
    else if(dragY != dragPrevY)
    {
       pSelectedCurrent->setPosition(ccp(pSelectedCurrent->getPositionX(),pSelectedCurrent->getPositionY()+(dragY-dragPrevY)/(abs(dragY-dragprevY)*movmentSpeed));
    }

}

答案 1 :(得分:1)

int moveX, moveY;
...

// First move
moveX = 0;
moveY = 0;
if sprite starts to move along the X axis
     moveX = 1;
else
     moveY = 1;

...

// General move handling
pSelectedCurrent->setPosition(cpp(
    pSelectedCurrent->getPositionX()+sign(dragX - dragPrevX)*movmentSpeed*moveX,
    pSelectedCurrent->getPositionY()+sign(dragY - dragPrevY)*movmentSpeed*moveY
    ));

// sign(x) = -1, if x < 0, 
//            0, if x = 0,
//            1, if x > 0