Question

I've got a common situation where you have two variables (xSpeed and ySpeed) which I want to independently set to zero when they fall below minSpeed, and exit when they're both zero.

What would be the most efficient method? Currently I have two methods (Method 2 being cleaner), but I was wondering if you guys knew a better way....

Method1:

bool isZeroX = Math.abs(xSpeed)< minSpeed;
bool isZeroY = Math.abs(ySpeed)< minSpeed;

if(isZeroX && isZeroY) return -1;
else if(isZeroX) xSpeed = 0;
else if(isZeroY) ySpeed = 0;

Method2:

if(Math.abs(xSpeed)< minSpeed) xSpeed = 0;
if(Math.abs(ySpeed)< minSpeed) ySpeed = 0;
if(ySpeed==0 && xSpeed==0) return -1;
Was it helpful?

Solution

You can do

if(-minSpread < xSpeed && xSpeed < minSpeed) {
    xSpeed = 0;
    if(-minSpread < ySpeed && ySpeed < minSpeed) {
        ySpeed = 0;
        return -1;
    }
} else if(-minSpread < ySpeed && ySpeed < minSpeed) {
    ySpeed = 0;
}

OTHER TIPS

I prefer your second example because it is the most readable. Prefer readability over efficiency unless you can prove that you should be optimising.

Perhaps make an elegant boolean method to see if the object is moving/stopped:

boolean isStopped() {
    if(Math.abs(xSpeed)< minSpeed) xSpeed = 0;
    if(Math.abs(ySpeed)< minSpeed) ySpeed = 0;

    return (ySpeed==0 && xSpeed==0);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top