user63898
user63898

Reputation: 30915

Looking for or algorithm or design pattern for Boolean selection

I have a situation where if one condition is met, the other conditions must be disabled even if they become true in the next stage.

Basically I have a method that is triggered each time a sprite is moved. I want to restrict movement to single axis, so when it starts to move on the x axis, it will be only able to move on the x until the drag is ended.

I'm looking for some kind of elegant way to do this instead of keeping observing 4 variable state.

E.g. in pseudo code I need to accomplish the following (for x axis):

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

And here's what I currently have:

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));
    }   
}

Upvotes: 0

Views: 93

Answers (2)

Alex F
Alex F

Reputation: 43331

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

Upvotes: 1

jambono
jambono

Reputation: 408

you can do that :

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));
    }

}

Upvotes: 1

Related Questions