PDA

View Full Version : subtract if true, add if false?


blank01
12-26-2010, 02:17 PM
Maybe it's just too early for me but I can't think of a way to simplify the following:

if(goLeft) {
this.x -= speed;
} else {
this.x += speed;
}

So far the best I can think of is:

this.x += (2*speed)*(int(goLeft)-.5)

It saves a few lines sure but I'm not sure if it will take less/more computer effort.

raikado
12-26-2010, 02:53 PM
there's no reason to do that. The first method is ok.

zyxstand
12-26-2010, 05:24 PM
also, you only need { and } if you want multiple lines of code. otherwise you can just do this:
if (goLeft) this.x -= speed else this.x += speed;
now it's also one line :P

raikado
12-26-2010, 10:00 PM
Also, another method would be this:

this.x += goLeft ? -speed : speed