Tuesday, March 30, 2010

Need help with simple AS3 coding

I'm just learning AS3 so please bear with me. I wrote the following code so that when the chair_btn is clicked the plant_mc will move across the stage:

chair_btn.addEventListener(MouseEvent.CLICK, movePlant);
function movePlant(myevent:MouseEvent):void{
?plant_mc.x-=100;
}

Now I would like to make it so if the user holds the shift key and clicks the mouse the plant moves in the other direction. How do I do that?

Thanks,

Laurie

Need help with simple AS3 coding

If I assume you mean they click the same button, then one way to approach it is to have a numeric variable, let's call it ''shiftUp'', and use that variable in your event handler function to control which direction to move.?You'll use the shift key to set that value to 1 or -1....

var shiftUp:int = 1;

chair_btn.addEventListener(MouseEvent.CLICK, movePlant);


function movePlant(myevent:MouseEvent):void{
?plant_mc.x-= shiftUp*100;
}

stage.addEventListener(KeyboardEvent.KEY_DOWN, changeDir);
stage.addEventListener(KeyboardEvent.KEY_UP, changeDir);

function changeDir(event:KeyboardEvent):void {
if(event.keyCode == Keyboard.SHIFT){
?if(event.type == ''keyDown''){
?shiftUp = -1;
?} else {
?shiftUp = 1;
?}
?}
}

Need help with simple AS3 coding

Yes, I did mean the user would click the same button. I'm sure your answer is the way I should do it, but to be honest, it is still more than I understand at this point.

I decided to change my idea a little and try this:

Already had this EventListener:

stage.addEventListener(KeyboardEvent.KEY_DOWN, detectText);
function detectText(myevent:KeyboardEvent):void {
?if (myevent.keyCode==36) {
?gotoAndPlay(''key press'');
?}

So I just added this:


?else if (myevent.keyCode==16) {
?plant_mc.x+=100;
?}
}

chair_btn.addEventListener(MouseEvent.CLICK, movePlant);
function movePlant(myevent:MouseEvent):void{
?plant_mc.x-=100;
}

It seems to be working and I think I understand this code since I already had an EventListener for detecting a key press. If you see any potential problems with the above code I would appreciate any feedback.

BTW, I'm saving the code you gave me for future reference! I hope to be playing around with it soon, so, thank you.

No comments:

Post a Comment