Be a Supporter!

As3 Tutorial: Toggle Quality With Q

  • 2,482 Views
  • 3 Replies
New Topic Respond to this Topic
chronicADRENLIN
chronicADRENLIN
  • Member since: Dec. 5, 2009
  • Offline.
Forum Stats
Member
Level 03
Blank Slate
As3 Tutorial: Toggle Quality With Q 2010-07-21 00:39:54 Reply

Alright! My first Flash tutorial!

This tutorial covers MAINLY how to implement code that lets the user toggle stage quality with the Q key, using ActionScript 3.0.
As a bonus, the code also explains key presses, removing event listeners, some optimization best practices, and SWITCH statements!

Just a small block of code that allows the player to toggle stage quality with the Q key. Enjoy!
Code is below, below that is the code described in detail.

//Import Flash Assets
import flash.events.KeyboardEvent;

//Keyboard Events for Controlling the Switching of Quality
var bToggleOncePerPress:Boolean=true;//TRUE sets button press to a single toggle per press/FALSE will constantly change quality while Q is held
var bQPress:Boolean=false;

stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDownQuality);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUpQuality);
if (!bToggleOncePerPress) {//Remove the event listener as it is unnecessary
	stage.removeEventListener(KeyboardEvent.KEY_UP,KeyUpQuality);
}

//Function Gets KEY_DOWN Input (Press Key)
function KeyDownQuality(e:KeyboardEvent) {
	if ((! bQPress)||(! bToggleOncePerPress)) {
		switch (e.keyCode) {
			case 81 ://Q
				//Press Q
				if (stage.quality=="LOW") {
					stage.quality="MEDIUM";
				} else if (stage.quality == "MEDIUM") {
					stage.quality="HIGH";
				} else if (stage.quality == "HIGH") {
					stage.quality="LOW";
				}
				bQPress=true;
				break;
		}
	}
}

//Function Gets KEY_UP Input (Release Key)
function KeyUpQuality(e:KeyboardEvent) {
	switch (e.keyCode) {
		case 81 ://Q
			//Press Q
			bQPress=false;
			break;
	}
}

Just copy and paste that code in Frame 1 of your .fla file and you're good to go! (Though make sure to Disable Keyboard Shortcuts in the test movie while testing it, of course >.< )

Line by line description of the code...

//Import Flash Assets
import flash.events.KeyboardEvent;

This imports the KeyboardEvent information for Flash to use. It's basically just a nice heads-up for the code itself, to let it know that a keyboard event is coming in the code below. The code can work without it, but it makes it run slightly faster and it's good optimization. Pro tip: if you have Flash CS5, it does this automatically for you when you create the KeyboardEvent function!

//Keyboard Events for Controlling the Switching of Quality
var bToggleOncePrePress:Boolean=true;//TRUE sets button press to a single toggle per press/FALSE will constantly change quality while Q is held
var bQPress:Boolean=false;

These two lines initialize the variables used in this code. Just two Booleans (vars that can hold only a 0 or 1, TRUE or FALSE): bToggleOncePerPress and bQPress.
bToggleOncePerPress is used by the coder to toggle if the player will have to press Q every time the player wants to change quality (TRUE), or if pressing and holding Q will make it cycle through the three quality levels really fast (FALSE). Having this as a feature is just a bit of polish and is not necessary, but I think it makes it just a little bit better. :)
bQPress is only really used if bToggleOncePerPress is TRUE. It's a boolean gate that is set to TRUE when Q is pressed, and FALSE when Q is released. This way, it only runs the actual code of pressing Q ONCE until Q is released again.
Note: I use personal naming conventions. When I create a variable, I use a prefix of the first letter, lowercase, of that variable type, followed by a descriptive name for the variable. For example, a boolean would be bVariable, and int would be iVariable, a timer would be tVariable, etc.

stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDownQuality);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUpQuality);
if (!bToggleOncePerPress) {//Remove the event listener as it is unnecessary
	stage.removeEventListener(KeyboardEvent.KEY_UP,KeyUpQuality);
}

This is adding the necessary event listeners to the stage. The first one, KeyDownQuality, listens for a KEY_DOWN, or key press, input. The second one, KeyUpQuality, listens for KEY_UP input.
Finally, the IF statement is (like the import event) not necessary for the code to run but just makes it run a little bit better. Essentially, it's saying: IF bToggleOncePerPress is NOT TRUE (! is the code equivalent of NOT), REMOVE the EVENT LISTENER KeyUpQuality.
Since bToggleOncePerPress is FALSE, holding down Q will cause quality to cycle while it's held. And since all KeyUpQuality does is reset bQPress so that it can be pressed again after it's released, it's not used if bToggleOncePerPress is false. So we can just remove it with the function removeEventListener, which saves the code from having to spend a couple cycles running code that's never going to get used. Best practices!

//Function Gets KEY_DOWN Input (Press Key)
function KeyDownQuality(e:KeyboardEvent) {
	if ((! bQPress)||(! bToggleOncePerPress)) {
		switch (e.keyCode) {
			case 81 ://Q
				//Press Q
				if (stage.quality=="LOW") {
					stage.quality="MEDIUM";
				} else if (stage.quality == "MEDIUM") {
					stage.quality="HIGH";
				} else if (stage.quality == "HIGH") {
					stage.quality="LOW";
				}
				bQPress=true;
				break;
		}
	}
}

First off, it's the KeyDownQuality function that gets a KEY_DOWN input - that's the first line.
The next line, IF, confirms one of two things: either if bQPress if FALSE, so the code only gets run ONCE per press, OR (the expression || is code for OR) bToggleOncePerPress is FALSE, so the code will run repeatedly while Q is held.
The following is a Switch statement. Switch statements are essentially glorified IF statements. In the Switch statement you place a variable (here, it's e.keyCode, or the KEYCODE of the key the user has toggled). Below, the CASE statements check the value of that variable. Since the KEYCODE for Q is 81, if the CASE (or the value of the variable held by the switch) is 81, it runs that CASE.
Note: if you want to change the key that toggles quality, just change the 81 by the case statement.
Here is a complete list of AS3 keycodes.

After that is the meat of this code. This IF statement checks the stage's current quality using the stage.quality variable. stage.quality is a string that holds one of four values: LOW, MEDIUM, HIGH, or BEST. (To include BEST in this code, just add another else if condition in that list, and add the term BEST. However, BEST only makes a difference if you're using bitmaps.) The IF statement first checks what the stage's current quality is, then sets it to the next quality by modifying the stage.quality string.

Next it sets bQPress to TRUE so that this code is only run ONCE if bToggleOncePerPress is TRUE. This will be reset to FALSE when the key is released.
Finally, the line break; is used to end a case statement within the switch. A single Switch statement can have multiple cases, but they must all be seperated by the line break;.

//Function Gets KEY_UP Input (Release Key)
function KeyUpQuality(e:KeyboardEvent) {
	switch (e.keyCode) {
		case 81 ://Q
			//Press Q
			bQPress=false;
			break;
	}
}

Last but not least, this block of code just resets the variable bQPress, so the next time the player presses Q it will continue cycling stage quality. If you've been following along so far, you should know what's going on here. The only real difference is the function itself, as it gets the KEY_UP input, or input when the player releases a key. See the last code block explanation for switch statements explanation.
Remember: if bToggleOncePerPress is FALSE this entire function is removed from the stage, and will never be run.

ALRIGHT! Now you know how to let the player cycle quality with the Q key, as well as some nifty things like switch statements, removing event listeners, and keycodes! I hope you find this useful!

-Nick

chronicADRENLIN
chronicADRENLIN
  • Member since: Dec. 5, 2009
  • Offline.
Forum Stats
Member
Level 03
Blank Slate
Response to As3 Tutorial: Toggle Quality With Q 2010-09-23 15:09:12 Reply

For those who care, here's an updated version of the above code. I'm not going to explain it like above, but it doesn't include anything really new, but rather just a more conveniently built system.
It includes several boolean variables that you can use to control how the script works, such as whether it cycles LOW > MED > HIGH > LOW or backwards, whether to include the BEST quality option, or if the player must also hold down the shift key as well.
Once again, just copy and paste the code onto its own layer on the first frame of your file and all is a-go! (Just be sure to check "Disable Keyboard Shortcuts" in the Control menu while testing!)
-Enjoy!

//Import Flash Assets
import flash.events.KeyboardEvent;

//Keyboard Events for Controlling the Switching of Quality
//Modifiable Variables - Change these variables to change how the script operates
var bToggleOncePerPress:Boolean = true;//TRUE sets button press to a single toggle per press/FALSE will constantly change quality while Q is held
var bLowToHigh:Boolean = false;//FALSE will cycle quality HIGH > MED > LOW > HIGH, where TRUE will cycle quality LOW > MED > HIGH > LOW
var bIncludeBEST:Boolean = true;//TRUE enabled the quality option for BEST (used to update quality of bitmap images, not vector (as in Flash-made graphics))
var bRequireShift:Boolean = false;//TRUE requires the user to hold down the Shift Key while pressing Q to cycle quality
var bRequireCtrl:Boolean = false;//TRUE requires the user to hold down the Ctrl Key while pressing Q to cycle quality

//System Variables - Please Do Not Modify!
var bQPress:Boolean = false;

//Initialize Events
stage.addEventListener(KeyboardEvent.KEY_DOWN,KeyDownQuality);
stage.addEventListener(KeyboardEvent.KEY_UP,KeyUpQuality);

if (! bToggleOncePerPress) {//Remove the event listener as it is unnecessary
	stage.removeEventListener(KeyboardEvent.KEY_UP,KeyUpQuality);
}

//Function Gets KEY_DOWN Input (Press Key)
function KeyDownQuality(e:KeyboardEvent) {
	if ((! bQPress)||(! bToggleOncePerPress)) {
		switch (e.keyCode) {
			case 81 ://Q
				//Press Q
				if (bRequireShift) {
					if (e.shiftKey) {
						if (bRequireCtrl) {
							if (e.ctrlKey) {
								UpdateStageQuality();
							}
						} else {
							UpdateStageQuality();
						}
					}
				} else {
					if (bRequireCtrl) {
						if (e.ctrlKey) {
							UpdateStageQuality();
						}
					} else {
						UpdateStageQuality();
					}
				}
				bQPress = true;
				break;
		}
	}
}

function UpdateStageQuality():void {
	if (stage.quality == "LOW") {
		if (bLowToHigh) {
			stage.quality = "MEDIUM";
		} else {
			if (bIncludeBEST) {
				stage.quality = "BEST";
			} else {
				stage.quality = "HIGH";
			}
		}
	} else if (stage.quality == "MEDIUM") {
		if (bLowToHigh) {
			stage.quality = "HIGH";
		} else {
			stage.quality = "LOW";
		}
	} else if (stage.quality == "HIGH") {
		if (bIncludeBEST) {
			if (bLowToHigh) {
				stage.quality = "BEST";
			} else {
				stage.quality = "MEDIUM";
			}
		} else {
			if (bLowToHigh) {
				stage.quality = "LOW";
			} else {
				stage.quality = "MEDIUM";
			}
		}
	} else if (stage.quality == "BEST") {
		if (bLowToHigh) {
			stage.quality = "LOW";
		} else {
			stage.quality = "HIGH";
		}
	}
}

//Function Gets KEY_UP Input (Release Key)
function KeyUpQuality(e:KeyboardEvent) {
	switch (e.keyCode) {
		case 81 ://Q
			//Press Q
			bQPress = false;
			break;
	}
}
ProfessorFlash
ProfessorFlash
  • Member since: Oct. 6, 2007
  • Offline.
Forum Stats
Member
Level 32
Programmer
Response to As3 Tutorial: Toggle Quality With Q 2010-09-24 12:01:50 Reply

Too much code tbh. Maybe someone can learn something by reading your explanations, but I don't recommend copy/pasting that clunky code. Here is same thing with the useless features cut out:

import flash.events.KeyboardEvent;

stage.addEventListener(KeyboardEvent.KEY_DOWN, toggleQuality);

var options:Array = ["LOW", "MEDIUM", "HIGH"];
var id:int = 2; //default is high

function toggleQuality(e:KeyboardEvent):void
{
	if (e.keyCode == 81) {
		id++;
		if (id > 2) id = 0;
		stage.quality = options[id];
	}
}

You can solve pretty much any problem you may have with AS3 by consulting the AS3 Language reference.