AS3 flash keyboard events spacebar issue - actionscript-3

hi guys thank you so much for trying to help
Ok so the question is this. I am trying to move a movieclip automatically with
movieClip.x += xspeed ;
ofcourse this works but the point is i want this to be triggered with keyboard press ..problem is i couldn't a keyboard event which works as a mouse click..it works as long as space bar is pressed but if i release it ..it stops working..i want it to be like onclick it should start moving automatically.
Any ideas? thanks
hi thanks so much for your reply and sorry for the delay. Your code gave me an idea but I tried to write it without classes . It doesnt throw up any errors however it doesnt work either . I must be doing something stupid , please have a look and let me know . //rope coding
var ropey = MovieClip(this.root).boat_mc.rope_mc.fishyrope_mc.hitbox_mc.y ;
trace(ropey);
var ropemove:Boolean;
stage.addEventListener(Event.ENTER_FRAME,ropeCode);
function ropeCode(e:Event):void
{
//detect keyboard spacebar click
stage.addEventListener(KeyboardEvent.KEY_UP,onSpacebarUp);
function onSpacebarUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.SPACE)
{
ropemove = true;
} else if(ropey > 600 ) {
ropemove = false;
}
}
//drop rope if variable = true
function dropRope(e:Event):void
{
if(ropemove = true) {
MovieClip(this.root).boat_mc.rope_mc.y += xSpeed;
} else if (ropemove = false) {
MovieClip(this.root).boat_mc.rope_mc.y -= xSpeed;
}
}
}

MyObj extends MovieClip (or Sprite). Basically alls that's happening is you should just toggle a variable when you get the KEY_UP (not KEY_DOWN, as that will repeat if the key is held down). Then, every frame, check this variable, and if's it's good, move
Something like:
private var m_shouldMove:Boolean = false;
// constructor
public function MyObj()
{
// add our listener for when we're added to the stage as we'll be adding events on it
this.addEventListener( Event.ADDED_TO_STAGE, this._onAddedToStage );
}
private function _onAddedToStage( e:Event ):void
{
// NOTE: the keyboard listener goes onto the stage
// you'll also need to remove the events when your object is removed (e.g. REMOVED_FROM_STAGE)
this.removeEventListener( Event.ADDED_TO_STAGE, this._onAddedToStage );
this.addEventListener( Event.ENTER_FRAME, this._onEnterFrame );
this.stage.addEventListener( KeyboardEvent.KEY_UP, this._onKeyUp );
}
private function _onEnterFrame( e:Event ):void
{
// every frame, if we should move, do so
if( this.m_shouldMove )
this.x += this.speed;
}
private function _onKeyUp( e:KeyboardEvent ):void
{
if( e.keyCode == Keyboard.SPACE )
this.m_shouldMove = !this.m_shouldMove; // toggle our var
}
Update
I've reworked your code sample, so it should work now:
var rope = MovieClip(this.root).boat_mc.rope_mc.fishyrope_mc.hitbox_mc;
var ropeMove:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, ropeCode);
stage.addEventListener(KeyboardEvent.KEY_UP, onSpacebarUp);
function onSpacebarUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.SPACE)
ropeMove = !ropeMove; // toggles ropeMove (i.e. if it's true, sets it to false, and vice versa)
}
function ropeCode(e:Event):void
{
// move the rope
if( ropeMove )
{
rope.y += xSpeed;
// stop moving if we've gone too far
if( rope.y > 600.0 )
{
rope.y = 600.0;
ropeMove = false;
}
}
}
What I changed:
Held your rope as a variable to make it easier to access
Removed ropey as it's not needed (for your > 600.0 check, you need to recalculate it anyway
The keyboard event is now added with the enter frame event (you were adding a new keyboard event every frame
The keyboard event listener just toggles the ropeMove var (there's no point checking for > 600.0 here as it means you only check when any other key is pressed)
The enter frame event simply moves the rope y
In the enter frame event, if our y is too big, we stop moving
What the code is doing:
We set up our vars - rope and ropeMove - ropeMove is used to know if we can move the rope or not
We add our event listeners - one for the keybard event, to catch the spacebar key, and one enter frame event, so we can move our rope if necessary
In the keyboard event, if our key is the spacebar, we toggle our ropeMove variable
In the enter frame event, if ropeMove is true, we move our rope
If our rope.y is greater than 600, we clamp it to 600, and set ropeMove to false so we stop moving
Update 2
With the addition of a variable ropeDir, the rope will now continuously move up and down (assuming ropeMove is true)
var rope = MovieClip(this.root).boat_mc.rope_mc.fishyrope_mc.hitbox_mc;
var ropeMove:Boolean = false;
var ropeDir:int = 1;
stage.addEventListener(Event.ENTER_FRAME, ropeCode);
stage.addEventListener(KeyboardEvent.KEY_UP, onSpacebarUp);
function onSpacebarUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.SPACE)
ropeMove = !ropeMove; // toggles ropeMove (i.e. if it's true, sets it to false, and vice versa)
}
function ropeCode(e:Event):void
{
// move the rope
if( ropeMove )
{
rope.y += xSpeed * ropeDir;
// stop moving if we've gone too far
if( rope.y > 600.0 && ropeDir == 1 )
ropeDir = -1;
else if( rope.y < 0.0 && ropeDir == -1 )
ropeDir = 1;
}
}

addEventListener(KeyboardEvent.KEY_DOWN, moveStarter);
function moveStarter():void
{
addEventListener(Event.ENTER_FRAME, startMove);
}

Related

ACTIONSCRIPT 3.0 seamless keyboard event

I am at a lost, which is not surprising for a beginner to encounter. Im attempting to execute a smooth and seamless keyboard direction command. Issue occurs when keys are held which creates a delay and fragmented like movement. code is below and please be gentle im new at this =)
var dx:Number = 0;
paddle.addEventListener(Event.ENTER_FRAME, motion);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
function motion (event:Event):void{
paddle.x = dx
}
function keyPressed(event:KeyboardEvent):void{
if(event.keyCode == Keyboard.LEFT){
dx -= 20;
}
if(event.keyCode == Keyboard.RIGHT){
dx += 20;
}
}
You basically keep track of when the key is pressed on KEY_DOWN and reset it on KEY_UP. Then, in your ENTER_FRAME, you check if the key is pressed, and move your paddle.
Something like this:
var isLeftPressed:Boolean = false;
var isRightPressed:Boolean = false;
stage.addEventListener( KeyboardEvent.KEY_DOWN, this._onKeyDown );
stage.addEventListener( KeyboardEvent.KEY_UP, this._onKeyUp );
paddle.addEventListener( Event.ENTER_FRAME, this._onEnterFrame );
// called when a key is pressed
function _onKeyDown( e:KeyboardEvent ):void
{
if( e.keyCode == Keyboard.LEFT )
isLeftPressed = true;
if( e.keyCode == Keyboard.RIGHT )
isRightPressed = true;
}
// called when a key is released
function _onKeyUp( e:KeyboardEvent ):void
{
if( e.keyCode == Keyboard.LEFT )
isLeftPressed = false;
if( e.keyCode == Keyboard.RIGHT )
isRightPressed = false;
}
// called every frame
function _onEnterFrame( e:Event ):void
{
// get our direction based on what key is pressed, and move our paddle
var dirX:int = ( isLeftPressed ) ? -1 : ( isRightPressed ) ? 1 : 0;
paddle.x += 20 * dirX;
}
This can easily be generalised for any key (keep a Vector.<Boolean> using the keyCode as an index) - Check out the PushButtonEngine KeyboardManager for the general gist: https://github.com/PushButtonLabs/PushButtonEngine/blob/PBE2/src/com/pblabs/input/KeyboardManager.as
You should move the object when you have a key pressed by the user until KeyboardEvent.KEY_UP event is dispatched to know when the user releases the key. Here is an example of what you are looking for:
Moving Movieclips using Keys with Acstionscript 3
I wish that it helps you. Good luck!

as3 space bar function not workingf

I have written a code to move a MovieClip on pressing space bar. So if someone presses space bar ..it activates a boolean variable from false to true and if its true the object moves ..but its not working. can some one please help. Thank you
var rope = MovieClip(this.root).boat_mc.rope_mc.fishyrope_mc.hitbox_mc;
var ropeMove:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, ropeCode);
stage.addEventListener(KeyboardEvent.KEY_UP, onSpacebarUp);
function onSpacebarUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.SPACE)
ropeMove = !ropeMove; // toggles ropeMove (i.e. if it's true, sets it to false, and vice versa)
}
function ropeCode(e:Event):void
{
// move the rope
if( ropeMove )
{
rope.y += xSpeed;
// stop moving if we've gone too far
if( rope.y > 600.0 )
{
rope.y = 600.0;
ropeMove = false;
}
}
}
This should work
var ropemove:Boolean = true;
var xSpeed = 5;
var once:Boolean=false;
stage.addEventListener(Event.ENTER_FRAME,ropeCode);
stage.addEventListener(KeyboardEvent.KEY_UP,onSpacebarUp);
function onSpacebarUp(e:KeyboardEvent):void
{
if (e.keyCode == 32)
{
if (ropemove==true)
{
if(once==false)
{
ropemove = false;
once=true
}
}
if(ropemove==false)
{
ropemove==true
}
}
if (rope.x >= stage.stageWidth )
{
ropemove = false;
}
trace(ropemove)
}
function ropeCode(e:Event):void
{
if (ropemove == true)
{
rope.x += xSpeed;
}
}
Two problems I can spot in your code:
1.) Everything is inside your Event.ENTER_FRAME event handler. This means every frame, that code is going to be run: including where you're adding a keyboard event listener. After 1 second, (assuming you are running at 30 fps) onSpacebarUp() will fire 30 times when you press space, and keeps increasing. Probably not a good idea, pretty sure you only want to add this once.
2.) The part where the boolean value will cause your movieclip to move is in a method: dropRope(). But this is not called anywhere, so it is actually not doing anything. Also may not need the event argument (the e:event) part, as you're not using it nor is it being called from an event.
BennettLiam's code should do something closer to what you want, I'm just adding this answer as an explanation for why your code isn't working. In their answer, they've fixed the above problems I mentioned: moved the event listener code for the keyboard outside of the event frame handler loop so it is only added once, and changed the enter frame event handler to call dropRope() o every frame, so that it is doing something.
var rope = MovieClip(this.root).boat_mc.rope_mc.fishyrope_mc.hitbox_mc;
var ropeMove:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, ropeCode);
stage.addEventListener(KeyboardEvent.KEY_UP, onSpacebarUp);
function onSpacebarUp(e:KeyboardEvent):void
{
if (e.keyCode == Keyboard.SPACE)
ropeMove = !ropeMove; // toggles ropeMove (i.e. if it's true, sets it to false, and vice versa)
}
function ropeCode(e:Event):void
{
// move the rope
if( ropeMove )
{
rope.y += xSpeed;
// stop moving if we've gone too far
if( rope.y > 600.0 )
{
rope.y = 600.0;
ropeMove = false;
}
}
}

Making an object or layer transparent when another object passes over it. (Flash Actionscript 3.0)

I'm very new to coding and am having trouble finishing the last little bit of a mini game type project for school.
So this is a draft of what the program looks like so far: http://aaronmillard.com/dir/wp-content/uploads/2013/08/Google-Doodle_Roomba.swf
Now what I want the program to do is "vacuum" up the google when the roomba drives over it. The easiest way to achieve this (I think) is to have an exact replica of the carpet layer without the google logo beneath the carpet layer with the google logo. So I would need to code something like "when the object(roomba) passes over object(carpetwithgooglelogo) make object(carpetwithgooglelogo) have 0 opacity." I just can't figure out how to say that in code.
The code as of right now look like this:
// Assign 4 booleans for the 4 arrow keys
var keyUp = false;
var keyDown = false;
var keyLeft = false;
var keyRight = false;
// Add the keyboard event (KEY_DOWN) on the stage
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressKey);
function pressKey(pEvent)
{
// If an arrow key is down, switch the value to true to the assigned variable
if (pEvent.keyCode == 38)
{
keyUp = true;
}
else if (pEvent.keyCode == 40)
{
keyDown = true;
}
else if (pEvent.keyCode == 37)
{
keyLeft = true;
}
else if (pEvent.keyCode == 39)
{
keyRight = true;
}
}
// Add the keyboard event (KEY_UP) on the stage
stage.addEventListener(KeyboardEvent.KEY_UP, releaseKey);
function releaseKey(pEvent)
{
// If the arrow key is up, switch the value to false to the assigned variable
if (pEvent.keyCode == 38)
{
keyUp = false;
}
else if (pEvent.keyCode == 40)
{
keyDown = false;
}
else if (pEvent.keyCode == 37)
{
keyLeft = false;
}
else if (pEvent.keyCode == 39)
{
keyRight = false;
}
}
// Set the velocity of the object
var speed = 4;
// And the rotation speed
var rotationSpeed = 6;
// Add an enter frame event on the moving object
myCircle.addEventListener(Event.ENTER_FRAME, circleEnterFrame);
function circleEnterFrame(pEvent)
{
// Set the default velocity to 0 if no key is pressed
var velocity = 0;
if (keyUp)
{
// If the key up is pressed set the new velocity to the speed value
velocity = speed;
}
if (keyDown)
{
// If the key down is pressed set the new velocity to the half speed value
velocity = -speed/2;
}
if (keyLeft)
{
// rotate the object
pEvent.currentTarget.rotation -= rotationSpeed;
}
if (keyRight)
{
// rotate the object
pEvent.currentTarget.rotation += rotationSpeed;
}
// Convert the degreeAngle to the radian angle
var angleRadian = pEvent.currentTarget.rotation / 180 * Math.PI;
// Move the object with the radian angle and the object speed
pEvent.currentTarget.x += Math.cos(angleRadian) * velocity;
pEvent.currentTarget.y += Math.sin(angleRadian) * velocity;
}
Any help would be very much appreciated! Thanks!
The easiest way is to do something like this:
if( roomba.hitTestObject(google)){
google.alpha = 0;
}
You'll have to check this on every frame using an ENTER_FRAME event.
If this is confusing tell me in the comments and I will clarify with more code.

AS3 Animation stop at frame 1

I'm really new at AS3, I used to be coding in AS2, but for more than a year I don't use Flash or ActionScript.
My problem is when I press left or right arrow which is defenied to move the character to right and left the animation just stop at the first frame. The idle animation works fine, but the walk animation starts and stop in frame 1 everytime I press the buttons.
vector.gotoAndPlay("parado");
var leftKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
var mainSpeed:Number = 7;
vector.addEventListener(Event.ENTER_FRAME, moveChar);
function moveChar(event:Event):void{
if(leftKeyDown){
if(vector.currentLabel!="andando"){
vector.x -= mainSpeed;
vector.scaleX=-1;
vector.gotoAndPlay("andando");
}
} else {
if(rightKeyDown){
if(vector.currentLabel!="andando") {
vector.x += mainSpeed;
vector.scaleX=1;
vector.gotoAndPlay("andando");
}
}
}
}
stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown);
function checkKeysDown(event:KeyboardEvent):void{
if(event.keyCode == 37){
leftKeyDown = true;
}
if(event.keyCode == 39){
rightKeyDown = true;
}
}
stage.addEventListener(KeyboardEvent.KEY_UP, checkKeysUp);
function checkKeysUp(event:KeyboardEvent):void{
if(event.keyCode == 37){
leftKeyDown = false;
}
if(event.keyCode == 39){
rightKeyDown = false;
}
}
FYI: "parado" is my idle animation and "andando" is my walk animation.
It's not stopping at frame 1, it's just being sent back to frame 1 all the time. Consider what happens when you hold down the button for a few seconds:
rightKeyDown starts as false. No code in that branch is executed.
User holds the right arrow, rightKeyDown becomes true
moverChar checks rightKeyDown, sees it's true and sends the character to "andando".
moveChar runs again, sees rightKeyDown is true but the character is still at the "andando" frame, so it does nothing.
Character goes to frame after "andando".
moverChar runs, rightKeyDown is still true, but the frame is not at "andando" anymore, so it resets back to it.
And that repeats during all the time the user is holding down the key, so it appears to be stuck in frames 1 and 2
A few alternatives to fix this problem:
Change the key frame only when the user presses or releases the button, not every frame in between.
function moveChar(event:Event):void{
if(leftKeyDown){
vector.x -= mainSpeed;
// No frame checks or frame changes here.
}
[...]
function checkKeysDown(event:KeyboardEvent):void{
if(event.keyCode == 37){
leftKeyDown = true;
vector.scaleX=-1;
vector.gotoAndPlay("andando");
// Send the character to the correct frame when the user presses the key.
}
[...]
function checkKeysUp(event:KeyboardEvent):void{
if(event.keyCode == 37){
leftKeyDown = false;
vector.gotoAndPlay("parado");
// Send it back to idle when the user releases the key.
}
[...]
Another option is to store each animation in a movieclip by itself and put them in a container movieclip. So there will be only two frames in the character's symbol, one for the idle animation and the other for the walking animation. In your code you use gotoAndStop instead of gotoAndPlay, so it doesn't matter if it's called every frame.
Edit: Also try to group your conditionals.
} else {
if(rightKeyDown){
if(vector.currentLabel!="andando") {
vector.x += mainSpeed;
vector.scaleX=1;
vector.gotoAndPlay("andando");
}
}
}
can be rewritten as
} else if (rightKeyDown && vector.currentLabel != "andando"){
vector.x += mainSpeed;
vector.scaleX=1;
vector.gotoAndPlay("andando");
}

Looping through an animation backwards AS3

Trying to get an animation to play backwards while a button is held down, which works fine, however when it gets to the first frame it just stops and won't loop back around to the last frame of the animation- how might one accomplish this? It seems like I need to break the event for a frame somehow and then start listening again...
backward_btn.addEventListener(MouseEvent.MOUSE_DOWN, setDownTrue);
backward_btn.addEventListener(MouseEvent.MOUSE_UP, setDownFalse);
addEventListener(Event.ENTER_FRAME, checkDown);
var isDown:Boolean = false;
function setDownTrue(e:MouseEvent){
isDown = true;
}
function setDownFalse(e:MouseEvent){
isDown = false;
}
function checkDown(e:Event){
if(isDown == true){
prevFrame();
if(currentFrame == 1){
gotoAndStop(120); //120 is the last frame of the animation
isDown = false;
}
}
}
Thanks!
The ENTER_FRAME event is not your problem, it continues to trigger. However, isDown turns into false on the last frame. You should change isDown = false; to isDown = true; after the gotoAndStop line in order to loop continuously.
I actually just helped a co-worker with this:
myMovieClip //your instance on the stage
lets say you want your movieclip to play backwards on click:
myMovieClip.addEventListener(MouseEvent.CLICK, onClick);
function onClick(e:MouseEvent):void
{
addEventListener(Event.ENTER_FRAME, playBackwards);
}
function playBackwards(e:Event):void
{
var frame:int = myMovieClip.currentFrame -1; //get frame before current;
myMovieClip.gotoAndStop(frame); // go to that frame
if(frame == 1) removeEventListener(Event.ENTER_FRAME, playBackwards); //if the frame is the first frame then remove the enterframe event
}
Save yourself some trouble and use totalFrames:
if(currentFrame == 1)
gotoAndStop(totalFrames);
else prevFrame();