What I would like to do is replace the two if statements with a single mathematical formula. I can’t for the life of me figure out how, as mathematics was never my strong point. Any advice would be greatly appreciated.
<script>
var x, y, z;
x = 200;
y = 100;
i = 0;
while(z != y) {
i++;
if (x < y) z = x + i;
if (x > y) z = x - i;
document.write(z + "<br>");
}
</script>
Edit: the real code looks like this. It’s not too pretty, was hoping I could shrink it down to two lines.
if (prevposX < newposX) posX = prevposX + animStep_;
if (prevposX > newposX) posX = prevposX - animStep_;
if (prevposY < newposY) posY = prevposY + animStep_;
if (prevposY > newposY) posY = prevposY - animStep_;
Edit:
It has been a while, but I believe the Modulus (%) operator would have helped me. I’ve now moved on to a library to do graphics for me so I didn’t need it in the end.
You can make use of a ternary operator
This assumes that when
x >= ythen you want to-i. If you want to stick exactly to your original you need a second ternary operator, which gets a bit messy:Frankly, it might be clearer to just keep it on 2 lines with 2 if statements like you already have.