Skip to main content
May 11, 2016
Question

how to move an object a fixed distance with 1 press

  • May 11, 2016
  • 1 reply
  • 346 views

I am using flash cs6

This is a very simple question but after trying several time in google i am still not able to fix this.

i have a hero which walk left and right if user hold down the button and change position 5 per frame.

Now what i want is if i press a key single time (not holding) then it will go/walk normally to a fix distance( lets say x +=50 ) and stop there.

here is my code

import flash.display.Stage;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.display.MovieClip;
import flash.events.Event;


var dPressed:Boolean = false;
var aPressed:Boolean = false;


stage
.addEventListener(KeyboardEvent.KEY_DOWN , keyDownHandaler);
stage
.addEventListener(KeyboardEvent.KEY_UP , KeyUpHandaler);
stage
.addEventListener(Event.ENTER_FRAME , gameLoop);

function keyDownHandaler(Devent:KeyboardEvent😞void
{
  
if (Devent.keyCode == Keyboard.D)
  
{
  dPressed
= true;
  
}
  
else if (Devent.keyCode == Keyboard.A)
  
{
  aPressed
= true;
  
}
}


function KeyUpHandaler (Uevent:KeyboardEvent😞void
{
  
if (Uevent.keyCode == Keyboard.D)
  
{
  dPressed
= false;
  hero
.gotoAndStop("hero Stand");
  
}
  
else if(Uevent.keyCode == Keyboard.A)
  
{
  aPressed
= false;
  hero
.gotoAndStop("hero Stand");
  
}  

}

function gameLoop(Levent:Event😞void
{
  
if (dPressed)
  
{
  hero
.x += 5;
  hero
.gotoAndStop("hero Move Right");
  
}
  
else if(aPressed)
  
{
  hero
.x -= 5;
  hero
.gotoAndStop("heroMove Left");
  
}

  
}

This topic has been closed for replies.

1 reply

Inspiring
May 12, 2016

Use:

var _keys: Object = {};

stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandaler);

stage.addEventListener(KeyboardEvent.KEY_UP, KeyUpHandaler);

stage.addEventListener(Event.ENTER_FRAME, gameLoop);

function keyDownHandaler(e: KeyboardEvent): void {

    _keys[e.keyCode] = true;

}

function KeyUpHandaler(e: KeyboardEvent): void {

   if (_keys[68] || _keys[65]) {

       _keys[e.keyCode] = false;

   hero.gotoAndStop("hero Stand");

   }

}

function gameLoop(Levent: Event): void {

    if (_keys[68]) //D {

        hero.x += 5;

        hero.gotoAndStop("hero Move Right");

    } else if (_keys[65]) //A {

        hero.x -= 5;

        hero.gotoAndStop("heroMove Left");

    }

};

///////////////////////

Note: Make sure that the labels are correct (heroMove Left & hero Move Right).