Looped action on button counting up (or down)

I’m kind of embarrassed I couldn’t figure this one out, I couldn’t find anything on either of the steps needed to pull this off, so I must be calling them by the wrong name or something.

What I’m doing is making a key listener so that when I hold down to the right, a number (in a text box) counts up, when I hold down left, it counts down. The range for the number is 0-255.

I assume I have to make a for loop that checks at a certain interval whether right or left is being pressed, then some sort of if statement seeing if it’s over 255 or under 0, but for some reason, I can’t figure out how to actually make any of that code.

So, do you have the code for the text box counting up and down working? If so, just add an if clause inside that action:


if (Number(_root.myTF.text) > 255) {
    trace("number greater than 255");
} else if (Number(_root.myTF.text) < 0) {
    trace("number less than 0");
}

You could also check that condition somewhere else, perhaps with a setInterval function, or whenever a certain button is pressed, etc.

Does that help?

-thesean

Yes, that definitely helps. I do not have the counting thing working, though, none of it. The problem is that I have a pretty good idea of what I have to do but no idea how to write the code I need.

So now we have the range limiter, just have to figure out how to write the hold button down and have it count up!

Here you go:

count = 0;
var keyListener:Object = new Object();
keyListener.onKeyDown = function() {
if (Key.isDown(Key.RIGHT) && count < 255) {
count++;
}
if (Key.isDown(Key.LEFT) && count > 0) {
count--;
}
myTextField.text = count;
};
Key.addListener(keyListener);

To display it in a dynamic textfield, change

trace(count);

to

myTextField.text = count;

Dude, seriously thank you so much. This not the first time you’ve saved me! Works like a charm!