actionscript-3,flash,adobe,motion , why doesn't this code detect diagonal motion?

why doesn't this code detect diagonal motion?


Tag: actionscript-3,flash,adobe,motion

"player" is an object that moves up , down , left and right when I press on arrow keys.

"player" doesn't move diagonally when I press up and left keys together or any other couple of keys.

I'm using Adobe flash CS5 and action script 3 ( As3 ), Would you tell me what the solution is ?

stage.addEventListener(KeyboardEvent.KEY_DOWN, detectText);     
function detectText(myevent:KeyboardEvent):void {
         var up:Boolean = false;
         var down:Boolean = false;
         var left:Boolean = false;
         var right:Boolean = false;
         var speedOfplayer:Number = 5 ;
 if (myevent.keyCode==39){
    right = true ;


 if (myevent.keyCode==37){
    left = true ;

 if (myevent.keyCode==38){
    up = true ;                     


 if (myevent.keyCode==40){
    down = true ;
            // if(right is true and left is not true)
            if( right && !left ) {
                player.x = player.x + speedOfplayer;
            // if(up is true and down is not true)
            if( up && !down ) {
                player.y = player.y - speedOfplayer;        
            // if(down is true and up is not true)
            if( down && !up ) {
                player.y = player.y + speedOfplayer;
            // if(down is true and up is not true)
            if( left && !right ) {
                player.x = player.x - speedOfplayer;


            // Move diagonally
            if( left && up && !right && !down ) {
                player.y = player.y - speedOfplayer;        
                player.x = player.x - speedOfplayer;

            if( right && up && !left && !down ) {
                player.x = player.x + speedOfplayer;
                player.y = player.y - speedOfplayer;        

            if( left && down && !right && !up ) {
                player.x = player.x - speedOfplayer;
                player.y = player.y - speedOfplayer;        
            if( right && down && !left && !up ) {
                player.x = player.x + speedOfplayer;
                player.y = player.y + speedOfplayer;



You may be overcomplicating things. This can be done in the following way. What is happening to the KEY_DOWN listener is that it will report the last key pressed. So you need a ENTER_FRAME listener to move the object. And because ENTER_FRAME will keep calling the function provided you need to capture if a key is released to reset the speed of the player to 0.

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
stage.addEventListener(Event.ENTER_FRAME, onTick);

var speedX:uint = 0;
var speedY:uint = 0;

function onKeyDown(event:KeyboardEvent):void {
     var key:uint= event.keyCode;

     if (key == Keyboard.UP) {
         speedY = -5;
     if (key == Keyboard.DOWN) {
         speedY = 5;    
     if (key == Keyboard.LEFT) {
         speedX = -5;
     if (key == Keyboard.RIGHT) {
         speedX = 5;

function onKeyUp(event:KeyboardEvent):void {
  var key:uint= event.keyCode;
  if (key == Keyboard.UP || key == Keyboard.DOWN) {
      speedY = 0;
  if (key == Keyboard.LEFT || key == Keyboard.RIGHT) {
      speedX = 0;   

function onTick(event:Event):void {
    player.x += speedX;
    player.y += speedY;


ActionScript: How to listen for an event from a different XML

I have a popup screen in which the player enters their name and clicks OK. When OK is clicked I want the player's name to be passed to the main XML. How can I do this? Here is the function in the main XML that handles the popup: private function...

AS3 - removeChild thinks it's working, but isn't removing anything (no error)

This is similar to a question I asked a couple of weeks ago, but different code and previous solution is not working. In a nutshell, I'm creating an array of tiles, the size of which can be selected via a dropdown menu. I want the previous grid to be removed...

Building a digital signage platform in HTML5

I need some feedback! So if any help, Thank you! I'm a developer for a digital signage company. We built a platform in Flash (ActionScript 3) and it has been running really smooth for a few years now. We've been talking about trying to move to HTML5, JQUERY and PHP...

ActionScript: How to call an objects function within an array?

In Java it is possible to set the datatype of an array, and by setting the datatype to the object I am using, I can call the methods and variables of that object. For instance: ArrayList<Object> name = new ArrayList<Object>(); name.add(new Object(variables)); name.get(0).method; Is there any way I can do...

ActionScript: Specification of the is operator

I am having trouble googling for the expected behavior of the is operator in AS3. What I need to know is what should happen if the left side is null. I know it is possible to test, and get empirical results, but I need to know what the specification says,...

action script 3 whole number as a division output

hello, I want to get whole number after division. x = 3/2; //results x = 1 and not 1.5 how to do this in as3??...

How to convert preg_replace from PHP to AS3?

I'm doing a fan Transformice map editor, but I've a question, "How can I do a preg_replace in Flash AS3?"... This is something like <? $mapXml = "<C><P /><Z><S><S L="304" H="65" X="175" Y="355" T="6" P="0,0,0.3,0.2,0,0,0,0" /></S><D /><O /></Z></C>"; $mapXmlDisplay = preg_replace('<S L="(.*)" H="(.*), etc..."', 'someThing', $mapXml); ?> It's possible? Thanks...

SCORM API wrapper and Flash in full screen

I lately posted this and unfortunately I couldn't figure it out why. Furthermore I haven't any solution for that. Today I realised I can switch between NORMAL and FULL_SCREEN without SCORM parts of the content (connect/disconnect, get/set, etc.). But when I check both Flash wrapper and Mike Rustici's edited API...

How to remove all Objects in For Loop?

Hey Everyone So I know this has to be really Simple I am over complicating it and can't figure out how to do it. So I have these stars moving in the background in my startScreen and I want to remove them when the Game starts. Here is How I...

A movie clip above a simple button makes it unresponsive

I have designed a menu in Flash CC which consists of several cloned buttons and an MC containing the text that is supposed to stay above the buttons. Each time a user switches the menu's page, AS commands the clip to switch to appropriate frames, therefore changing the text above...

AS3 : How to compare 2 array containing objects using 1 for loop only?

I have 2 array having objects of different length var arr : Array = [{name : "aa", id : "0"}, {name : "bb", id : "1"}, {name : "cc", id : "2"}]; var arrTemp : Array = [{name : "ee", id : "0"}, {name : "hh", id : "1"}, {name...

Flash CS6 / AS3: Drag and Resize a rectangle movieclip

Not sure if this is possible but going to ask: is there a way of being able to resize a symbol (in this case, a movie clip) in an swf file by clicking and dragging it with your cursor? One of the things I need to do is have a...

Is there a class in AS3 that tells you the type of the URL protocol?

Is there a class in AS3 or Flex that tells you the type of protocol a URI or URL is part of? I was sure there was a class that broke a URL into various parts and grouped it into usable data. For example, if the URL is, "mailTo" it...

converting XML data into an array of objects AS3

I'm using Flash AS4 and Ive created and array that holds xml data which works fine with the following loop for(var i:int = 0; i < uNavXML.length(); i++){ navArray.push(uNavXML..navRef.text()[i]); The XML data is actually the names of movie clips that I have on stage: xmlLIST :<uNav> <unavNavID>1</unavNavID> <navRef>navBtns.nav01</navRef> </uNav> <uNav>...

Adobe Flash CS6 AS3: KeyUp Handler triggers immediately after KeyDown Handler

So in my code I was attempting to make it where you had two players, each player had their own key down and key up handlers, clearly labelled in my attached code, and in their I handle the movement, player one has WSAD and player two uses the Left, Right,...

How can hitTestObject work for many objects?

I have a game where player moves forward over (semi)random tiles. I want a hittest for when the player hits a certain tile. However when the char hits one of the spawned in floor2's nothing happens. I think this is because there are multiple 'floor2' movieclips on the stage ?...

AS3 - Score counter

I am making a simple math game with four frames. In the first frame you can choose the math operation you want to practice. In the second frame you are presented with a randomly generated math question. If you enter the correct answer, the application outputs "correct answer", and skips...

Rails AJAX Feedback, especially on error

I'd like to improve the AJAX feedback in my application (after I POST a remote form in my modals, etc.). I already have some nice feedback showing a loading animation $(document).ajaxStart(function(){ $('.loading-feedback').show() }) $(document).ajaxStop(function(){ $('.loading-feedback').hide() }) But I realize it's not enough : when my AJAX requests trigger a Completed...

Actionscript 3 Search for string in array, propblem

I have a problem with searching for strings in an array. I want to search for one word and if it exists, I want to trace the position of the string in the array. I believe it should be something like this: if (myArray contains "11111111") { trace("*position*") } else...

how to fix error 1009 in as3

hi i have been searhing the net for hours and have not found a solution to my problem and i have no idea how to fix it as i am only new to flash so if you know anything that might help me just comment below please all help is...

Responsive sized swfobject?

I have embedded this interactive poster ( ) into an html page but am having trouble setting the size of it. I am working with bootstrap and want the content to be responsive but at the moment it comes up really small sits in the middle of the column...

AS3 can't find the load method on a Loader

I'm trying to load an image from the internet with AS3 following this tutorial. When I try to compile the application I get the following error: Call a possibly undefined method load through a reference with static type Loader. my_loader.load(where, loaderContext); ^ Here is the code I'm using: package {...

type conversion if flex

I am using Flerry as Java-Flex bridge for my Flex Desktop Application. How to convert List in Java to ArrayCollection in Flex Flex Code:- [Bindable]public var screenList:ArrayCollection; <flerry:NativeObject id="windowControllerObj" source="ls.window.EnumAllWindowNames" singleton="true" fault="windowControllerObj_faultHandler(event)"> <flerry:NativeMethod id="getWindowNames" name="getAllWindowNames" result="windowControllerObj_resultHandler(event)" fault="getWindowNames_faultHandler(event)"/>...

AS3: Fast hovering doesn't execute rollOut

I'm having a serious problem that is getting me nervous: I've made a button _btn that includes ROLLOVER and ROLLOUT animations with coding (an nested movieclip instance called barra that increases to half alpha when you hover over and decreases when you hover out). [Here it should go a descriptive...

Can't parse XML AS3 in flash with namespaces [SOLVED]

I don't understand why I can't parse these datas : <places yahoo:start="0" yahoo:count="1" yahoo:total="1" xmlns="" xmlns:yahoo=""> <place yahoo:uri="" aaa:lang="en-US" xmlns:aaa=""> <woeid>23424819</woeid> <placeTypeName code="12">Pays</placeTypeName> <name>France</name> <country type="Pays" code="FR"...

Remove click after going to another scene in AS3?

After switching to my 2nd scene, the keyboard event does not work until I left-click the screen. How to avoid that left click so that I can trigger my keyboard event directly right after moving to my 2nd scene? More details you may need: 1st Scene btnStart.addEventListener(MouseEvent.CLICK, initGame); function initGame(e:MouseEvent)...

How to know fast if another computer is accesible in AS3 (Adobe Air)

I'm using FileStream to read files in two computers that are connected in a Local Area Network (LAN). I have no problem to read the files when the others computers are connected. I'm checking if the directory exists before writing the file I'm checking if the directory AND the file...

How make with AS3 downloading MP3 files in the background mode and plays it?

I need help with AS3 make downloading MP3 files in the background mode. Man goes to my site and it will automatically load MP3 file on his computer and plays it. I read these examples here but do not know how to do it? Prompt what code and how...

Activerecord Rails 4 perform something like a join that still returns rows that don't have the association

If after reading my question you have a suggestion for a better title, please add a comment. I was having trouble succinctly saying what I wanted. I have a situation like this. class Artist < ActiveRecord::Base has_many :album_artists has_many :albums, :through => :album_artists end class Album < ActiveRecord::Base has_many :album_artists...

Flash analysis for Chrome Extension

I'm reading a tutorial on how to create your own Chrome Extension using Javascript/HTML/CSS. I wanted to practice a bit on a facebook flash game to make my life easier, you know what i mean BUT i don't know how to read flash memory online or how to analyse the...

How to raise a seek to event for a Flash MediaElement using iframe?

How can a seek event be raised to a Flash MediaElement, starting from an embed code with defaults flashvars. Such as: <embed id="me_flash_0" name="me_flash_0" play="true" loop="false" quality="high" bgcolor="#000000" wmode="transparent" allowscriptaccess="always" allowfullscreen="true" type="application/x-shockwave-flash" pluginspage="//" src="/dl/player/Fallback/flashmediaelement.swf"...

Why isn't this php math code working

Hey guy's so am trying to convert this as3 code to php but its not working correctly i need it like the as3 one generating thanks! PHP: print(floor(rand() * 1000) + 3000); Result:28240000 AS3: var intCID = Math.floor(Math.random() * 1000) + 3000; var strSessionId = String(intCID); trace(strSessionId); Result:3330...

Dynamic Text doesn't show up through code

if I make a dynamic text on the stage, name it something like "output" And I write in the enterframe. output.text = "Something"; It doesn't even show up in the stage, and the text box is blank....

Error #1502: A script has executed for longer than the default time period of 15 seconds

this is my first time using AS3 so I apologise if the cause of this problem is painfully obvious. I'm making chess and I've got a class for each piece on the board. When it's player 1's turn, all the black pieces should wait to be clicked, but when I...

Including library in AIR Native Extension causes the error, “The extension context does not have a method with the name…” for all methods

I am working on an AIR Native Extension (ANE) for Windows desktop. The point of this extension is to be able to call out to a third-party C library, which consists of two .h files defining the method signatures/typedefs, and a .lib file. Before including the third party library in...

Problems with Flash 8 (AS2), Timelines, and Variable Scopes

Okay, so trying to not post 5 pages of information, I'll start with the following: In a movie clip, I have 3 keyframes. I'm trying to edit a textbox on each frame, but I've found previously that only the text box in the current frame is accessible. In an attempt...

AS3 LocalConnection: function is not firing

I'm building an AIR app that sends text string to a swf-file. When I export the sender and reciever apps to swf and run them in Flash players, everything works well. But when publishing the sender app to AIR things don't work anymore. I think the connection works, because there...