Making my character talk with a speechbubble using 2 actionscript3 (info below) - actionscript-3

I've been taking a computer programming class for high school and I've been stuck on this problem for longer than I'd like to admit. I'm in a program that basically sets it up so you work at your own pace with a teacher and no classmates that know what I'm doing so basically I'm teaching myself to some extent.
Okay so my job is to make a speech bubble I made pop up when I click on my character using the script I made for my character (Shippo.as) and the speech bubble made this activity for assignment 1 (SpeechBubble.as).
So far when I run the program my character pops up, but when I click on him nothing happens. I get no errors or anything so the problem is with the code but I'm unable to spot it. I will display the codes for everything below by the names I'm using for them to hand in.
- U1A6As2 - Talking Character
import Shippo;
import SpeechBubble;
var shippo_mc:Shippo = new Shippo;
addChild(shippo_mc);
shippo_mc.x = 250;
shippo_mc.y = 200;
(this code creates and displays my character named Shippo.)
- SpeechBubble.as
package
{
import flash.display.MovieClip;
import mc_SpeechBubble;
import Shippo;
public class SpeechBubble extends MovieClip
{
public function SpeechBubble (xPosition:Number, yPosition:Number, message:String)
{
var bubble_mc:MovieClip = new mc_SpeechBubble();
bubble_mc.x = xPosition;
bubble_mc.y = yPosition;
bubble_mc.speechText_txt.text = message;
addChild(bubble_mc);
}
}
}
(This code is from the tutorial from Activity 6, Assignment 1, the only thing I added was import Shippo;)
- Shippo.as
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import mc_SpeechBubble;
import SpeechBubble;
public class Shippo extends MovieClip
{
public function Shippo()
{
trace ("Click me and I'll talk.");
this.addEventListener(MouseEvent.CLICK, shippoTalk);
}
public function shippoTalk(event:MouseEvent):void
{
var bubble:SpeechBubble = new SpeechBubble(350,50,"Hello, my
name's Shippo.");
addChild(bubble);
this.removeEventListener(MouseEvent.CLICK, shippoTalk);
}
}
}
(The only reason the trace ("Click me and I'll talk."); is in the code is just so I know that part is working correctly, it's not needed. I think the problem lies in the shippoTalk function but not sure how to fix it because the code in shippoTalk is the one used during assignment 1 of activity 6.)
Keep in mind I'm no flash pro and I don't know the language to well so bear with me, I'm trying to stick with what I have learned and not go to far off the rails but in all honesty as long as this gets done I will be happy, any help will be good help.

You've mis-spelled 'function' as 'funtion' in your mc_SpeechBubble constructor method.
Also f.y.i., you don't have to use most of your 'import' statements if your classes are all in the same package.

Related

AS3 || Using same function with different variables

I'm very new to AS3 and I'm trying to learn by experimenting in flash, by making a simple 2D farming game with very simple code.
I've made one crop field out of 6 that works, which is a movieclip with different frames for each fruit growing. For example, frame 1-5 is a strawberry growing where frame 5 is when it's ready to be picked, and then 6-10 is of carrots, etc
Is there a way for me to make it so that I don't have to write the exact same code for the next crop field, and instead change the variables in this code depending on which crop field you click on?
Here's an example of the code
if (field1.currentFrame == 1)
{
field1.nextFrame();
infoText.text = "You've watered the crop. Let's wait and see how it turns out!";
function plantStrawberry():void
{
field1.nextFrame();
if (field1.currentFrame == 5)
{
clearInterval(strawberryInterval);
}
}
var strawberryInterval = setInterval(plantStrawberry,5000);
}
pls no judgerino, as said, I'm very new to AS3, lol.
There are a few ways to go about being DRY (don't repeat yourself) with your code in this scenario. The best way, would be to learn to use classes. Classes are blueprints, and are made for these very scenarios.
Here is an example of a simple class to do what you'd like. In Flash/Animate, go to file, then new, then 'ActionScript 3.0 Class' - give it a name of Crop.
In the document that comes up, there should be some basic boilerplate code. Everything should wrapped in a package. The package tells flash where to find this class - so this example, leave it as is (just package {) and save this file in the same folder as your .fla. All functions need to be wrapped in a class declaration, this should be generated for you based off the name you put in (Crop). Next you'll see one function, that has the same name as the class. This is called a constructor, and this function runs whenever you create a new instance of this class. Since classes are blueprints, you create instances of them that are objects - those objects then get all the code you put in this class.
So, to start, you should have this:
package {
public class Crop {
public function Crop() {
// constructor code
}
}
}
Let's go ahead and put your code in. See the code comments for details:
package {
//imports should go here
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
//lets make this class extend MovieClip - that means it will be a MovieClip in addition to everything else you add below
public class Crop extends MovieClip {
//instead of setInterval, use a timer - it's easier to manage and cleanup
//in class files, variables and functions have access modifiers, that's what the public and private words are about
//private means only this class can ever use the var/function
private var timer:Timer;
public function Crop() {
//initialize the timer - have it tick every 5 seconds, and repeat 4 times (to move you from frame 1 - 5)
timer = new Timer(5000, 4);
//listen for the TIMER event (which is the tick) and call the function 'grow' when the timer ticks
timer.addEventListener(TimerEvent.TIMER, grow);
}
//a function that starts the timer ticking
public function startGrowing():void {
timer.start();
}
//this function is called every timer tick.
private function grow(e:Event):void {
this.nextFrame(); //go to the next frame of your crop
}
}
}
Save the file. Now that you have this class, you need to attach it to your library assets so they all get this functionality.
In the library panel, for each of your crop objects, right click (or ctrl+click on Mac) and go to properties. In the properties, click advanced, and give it a unique class name (for instance Strawberry). Then in the base class field, put Crop (the class we just made). Repeat for the others.
Now on your timeline, when you want a crop to start growing, you can do:
field1.startGrowing(); //assuming your instance `field1` is one of the crops that you assigned the base class `Crop` to
Hopefully this gives an entry point into the power of classes. You can add more functionality into this one and it automatically apply to all the crops you attached it to.
Although BFAT's tutorial is absolutely correct, it is not the only way to do things, moreover, if you ever move from Flash and AS3 to something else, or even try Starling (a framework that allows to build fast and non-laggy mobile applications in Flash/AS3), you'll find that concept not applicable. It is very Flash-y and I applause to it though.
Instead of making each field subclass the abstract (means, it is never instantiated by itself) Crop class, you can make the Crop class take 1 of these 6 fields as an argument on creation (or later). Basically, you tell "I want to make crop field with wheat graphics". So, let me redo that class a bit.
package
{
// Imports.
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.Event;
import flash.events.TimerEvent;
public class Crop extends Sprite
{
// I agree with the use of Timer.
private var timer:Timer;
// Visuals go here.
private var field:MovieClip;
// Class constructor.
public function Crop(FieldClass:Class)
{
// With "new" keyword you can omit ()
// if there are no mandatory arguments.
field = new FieldClass;
field.stop();
addChild(field);
}
// A function that starts the timer ticking.
public function startGrowing():void
{
timer = new Timer(5000, 4);
timer.addEventListener(TimerEvent.TIMER, grow);
timer.start();
}
// This function is called every timer tick.
private function grow(e:Event):void
{
// Command the graphics to go to the next frame.
field.nextFrame();
}
}
}
Then, the usage. When you create fields, you need to set AS3 classes to them to have access, leaving base class as is, Flash will automatically set it to non-specific MovieClip. Lessay, you have crops.Wheat field and crops.Barley field.
import Crop;
import crops.Wheat;
import crops.Barley;
var W:Crop = new Crop(Wheat);
var B:Crop = new Crop(Barley);
addChild(W);
addChild(B);
B.x = 100;
W.startGrowing();
B.startGrowing();

AS3 Setup Buttons for All Frames in Document Class

I'm making a simple interface with Flash. Let's say we've got:
frame 1: 1 button that advances to frame 10 (goto10)
frame 10: 2 buttons, one advances to frame 20 (goto20), one opens a URL (openURL)
frame 20: 3 buttons, one goes back to frame 1 (goto1), one goes to frame 10 (goto10), and one opens a URL (openURL)
package {
import flash.display.MovieClip
import flash.events.Event;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.display.SimpleButton;
public class NKE_DocumentClass extends MovieClip {
public var goto1:SimpleButton = new SimpleButton();
public var goto10:SimpleButton = new SimpleButton();
public var goto20:SimpleButton = new SimpleButton();
public var openURL:SimpleButton = new SimpleButton();
public function NKE_DocumentClass() {
goto1.addEventListener(MouseEvent.CLICK,function(self:MouseEvent):void{clickGo(self,1)});
goto10.addEventListener(MouseEvent.CLICK,function(self:MouseEvent):void{clickGo(self,10)});
goto20.addEventListener(MouseEvent.CLICK,function(self:MouseEvent):void{clickGo(self,20)});
openURL.addEventListener(MouseEvent.CLICK,function(self:MouseEvent):void{urlGo(self,"http://google.com")});
}
public function clickGo(event:MouseEvent, nextCue:int):void {
gotoAndStop(nextCue);
trace("Advanced to: " + nextCue);
}
public function urlGo(event:MouseEvent, goURL:String):void {
var request:URLRequest = new URLRequest(goURL);
new URLLoader(request);
trace("Executed URL: " + goURL);
}
}
}
Problem is, once I leave frame 1, none of the buttons work... they're simply unresponsive. It seems like the code doesn't stay loaded once it leaves frame 1.
Thoughts?
I'm pressuming the problem is because when this code is first executed (as a Document Class) the only button that exists is the button on frame 1? This is under the assumption than you've created buttons in the Flash IDE then added them to the stage from the library on the specific keyframes.
I see you've created the SimpleButtons programmatically but since they haven't been added to the stage in the code you've shown, the presumption is that you've just called them the same names as the buttons you've placed on stage? Correct me if I'm wrong and I'll try to offer some other advice if the below doesn't help.
One solution would be to create them all on the first frame then switch their visibility on and off depending on when you need them.
If you're not sure how:
goto10.visible = false;
etc etc
I can't remember now without testing but if you have placed them all on the stage on different keyframes this may cause a problem.
Back in the days of putting code on the timeline if you put code on frame 1 but it referenced objects that weren't on frame 1 then the code would fail (this is probably what's happening with your document class - it's running when not all objects exist).
I would make sure they're all on one layer without any keyframes, from frame 1, and you just switch their visibility on and off. Alternatively, let your classes add and remove the buttons and other interface elements and don't use the timeline at all.

How to change the value of a certain variable in the document class through another class?

here is my problem. In my document class TowerDefenseGame.as, I defined a variable Turrent1Flag:
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Sprite;
import flash.display.Shape;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFieldType;
public class TowerDefenseGame extends MovieClip
{
public var Turrent1Flag==0;
}
public function TowerDefenseGame()
{
......
}
Now, in another class Turrent1Button.as, I need to create a mouse click event, by which the Turrent1Flag is set to 1:
package
{
import flash.display.MovieClip;
import flash.events.*;
import flash.display.Sprite;
import TowerDefenseGame;
public class TurretButton1 extends MovieClip
{
public var ButtonBase:Sprite=new Sprite();
public var TurretBase:Sprite=new Sprite();
public var Gun:Sprite=new Sprite();
public function TurretButton1()
{
......
this.addEventListener(MouseEvent.CLICK, MouseClick);
}
public function MouseClick(event:MouseEvent):void
{
MovieClip(root).Turret1Flag = 1;
}
Well, this does not work. I am using Adobe flash cs6 and it says the value cannot be accessed. Someone know how to do this?
try this:
private static var _instance:TowerDefenseGame;
public static function get instance():TowerDefenseGame { return _instance; }
public function TowerDefenseGame()
{
_instance = this;
}
public function MouseClick(event:MouseEvent):void
{
TowerDefenseGame.instance.Turret1Flag = 1;
}
So, to start out, AS3 makes it difficult to so what you've been used to doing in AS2 on purpose, to allow for better Object Oriented practices. When you maintain high and tight walls between Classes, it becomes easier to change Class A without having any effect whatsoever on Class B. Class B only knows about the doors and windows that are the "official" ways into the house of Class A, so it doesn't matter if you move the couch. You also make it extremely easy to replace Class A with Class C that has similar doors and windows.
When you reach through the walls by introducing global state, you can't replace Class B with Class C without changing Class A, because Class A has a direct reference to Class B and knows exactly where the couch is.
One way to handle this is through Inversion of Control (IoC). So, for our house, the couch might be supplied from outside and whatever component supplied it might keep a reference to it, so it would be able to access the couch no matter where in the house it went. So, you might choose to create your TurretButton and pass that into whoever owns that, while your TowerDefenseGame keeps a reference to it and listens directly to it, changing its own flag in response to the click.
Looking at your code, you probably don't need to go that far, because I don't see any sign that your TurretButton is actually nested. In that case, you can listen directly to it, whether you're creating it on the stage or creating it through code (which I'm not a fan of). If you're using the stage in the IDE and it exists on the stage, then just create a public variable of type TurretButton (or you could probably use SimpleButton since you no longer have need for a special Class here based on the code you've shown). That instance will be available in the constructor of your TowerDefenseGame. Just add your event listener to it, and then the listener and the variable you want to change are in the same scope. Ergo, the problem you were trying to solve never existed--you were simply looking at the problem from a perspective that overcomplicated things.
If, in fact, your code is nested in a way that's not shown, you can use ActionScript 3's event system, which is fabulous, to handle the issue without introducing direct coupling and without having to create the button through code and push it down to where it's used. One way is to just listen for any mouse click (since that is a bubbling event) and look to see what was clicked. Another solution is to generate a custom event from the button that you can then listen to from the top level to change the flag. That would look something like:
package view.button {
public class TurretButton extends MovieClip {
public function TurretButton() {
super();
mouseChildren = false;
addEventListener(MouseEvent.CLICK, broadcastTurretEvent);
}
protected function broadcastTurretEvent(e:Event):void {
dispatchEvent(new Event('turretClicked', true));//the true parameter makes it bubble
}
}
}
Then your tower Class would look like
package {
public class TowerDefenseGame extends MovieClip {
//the fact that you're calling it Turret1Flag suggests you're going to have more than 1
protected var turretFlags:Array /*of Boolean*/ = [false, false];
//your turret button instances
//doesn't show nesting, this is just to indicate that
//these are named instances so you know how what they're called
//they could be nested at any level
public var turret1:TurretButton;
public var turret2:TurretButton;
//...etc.
public function TowerDefenseGame() {
super();
addEventListener('turretClicked', onTurretClicked);
}
protected function onTurretClicked(e:Event):void {
//you can also just extract the number and do the math
//to get the correct array index
switch(e.target.name) {
case 'turret1':
turretFlags[0] = !turretFlags[0];
break;
case 'turret2':
turretFlags[1] = !turretFlags[1];
break;
}
}
}
}
Note how well this scales. You don't have to have a different Class for each button to change each separate flag. It's also easy to add more buttons without a whole lot of code changes. You could take this solution further and create a custom event that has a property that says which button was clicked, and you could supply the value to use to that for the button through dependency injection, etc.
I also made the assumption in my code that flags should be boolean and that they're turning on with the first click and off with the second click, etc. You could take the same idea and change it to, for example, increment with every click. I suspect you don't actually want to do what your code was showing and just turn it on with the first click and just leave it on forever.
Another note is that if you think you might want to code in AS3 over the longer term, you should probably learn the coding conventions that are used in AS3. One of these is that Class names start with a capital letter, but properties and methods do not.
It's probably not a great habit to get into for everything, but a static variable looks like it would work here.
public class TowerDefenseGame extends MovieClip
{
public static var Turrent1Flag = 0;
}
In Turrent1Button.as:
public function MouseClick(event:MouseEvent):void
{
TowerDefenseGame.Turret1Flag = 1;
}

as3 calling a function in another class [duplicate]

UPDATE: OK I am about ready to give up on Pacakages and classes. No answers coming. Not sure what to do. I tried to make the question easier and made a new post but I was down voted for it. as3 calling a function in another class
I am TOTALLY NEW to using PACKAGES and CLASSES. I am finally converting over from the timeline after having so many issues. Please be patient with my lack of knowledge. I need to know how to call a function in the child swf file I loaded from code in the maintime in the parent swf.
There are 2 swf files. Main.swf and pConent.swf
1. Main.swf has code in the timeline of the first frame.
2. pConent.swf is loading a PACKAGE CLASS as file.
QUESTIONS
I am trying to call a function in it from its parent Main.swf. How do I do this?
Here is sections of the code from both. Thanks
Main.swf CODE /// is an AIR for Andrid swf
function LoadContent()
{
TheContent.load(new URLRequest( "pContent.swf"));
TheContent.contentLoaderInfo.addEventListener(Event.COMPLETE, LoadContentTWO);
function LoadContentTWO(e:Event)
{
Content = TheContent.content as MovieClip;
pContent = Content as Object;
addChild(TheContent);
var OSS:String = "device";
trace(pContent); //// comes out as: [object pContent]
pContent.GetOnlineStatus(OSS); ///// HOW DO I GET THIS TO CALL FUNCTION
}
}
A SECTION OF THE "CLASS" in pContent.swf I am trying to call
public function GetOnlineStatus(OS:String)
{
if(OS=="online")
trace("inside ONLINE" );
}
if(OS=="device")
{
trace("inside DEVICE" );
}
}
THE ERROR I AM GETTING
TypeError: Error #1006: GetOnlineStatus is not a function.
UPDATE: I decided to post the FULL PACKAGE ( my first) to see if I am doing it right.
package
{
import flash.display.MovieClip;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
import flash.display.*;
import flash.media.Sound;
import flash.system.*;
import flash.media.SoundChannel;
import flash.display.MovieClip;
import flash.events.MouseEvent;
public class pContent extends MovieClip
{
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
var ScreenY = flash.system.Capabilities.screenResolutionY;
var ScreenX = flash.system.Capabilities.screenResolutionX;
var swf:String;
var daSounds:String;
var images:String;
var videos:String;
var OnlineStatus:Boolean;
//++++++++++++++++++++++++
//++++++++++++++++++++++++
public function pContent()
{
BG.addEventListener(MouseEvent.CLICK, mouseHandlerdown);
}
//++++++++++++++++++++++++
//++++++++++++++++++++++++
//-------- * FUNCTIONS * --------
//-------------------------------
public function mouseHandlerdown(event:MouseEvent):void
{
alpha = .3; // testing
}
public function GetOnlineStatus(OS:String)
{
if(OS=="online")
{
OnlineStatus = true;
Security.allowDomain("*");
trace("inside THE PATH " + ThePath.text);
daSounds = "http://mycontactcorner.com/upload/files/";
swf = "http://mycontactcorner.com/upload/files/";
trace("inside THE DEVICE ONLINE" );
OnlineStatus = false;
swf = "";
daSounds = "content/sounds/";
//LoadMenu();
LoadStage();
LoadBeau();
}
if(OS=="device")
{
trace("inside THE DEVICE ONLINE" );
}
}
//------ * END FUNCTIONS * -----
//------------------------------
}// END FUNCTION pContent
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
}//// END PACKAGE
Don't be disappointed, but I won't have a "real" answer to your question, and I am really not going to work through all of your code to solve it, either. It is your own task to learn how to do this, and unless people here are very, very hungry for reputation, no one will do it for you - we will only help you to find the right way.
Your problem is not "packages and classes", so please do not give up on them. They will help you a great deal, once you've started to understand them. Your problem is, that you are not facing a single problem, but actually at least two (and quite substantial ones, I might add):
You need to go back to learn about the basics of object oriented programming in ActionScript. You won't have much luck getting answers to questions like this, otherwise. And believe me, I don't mean that in a patronizing way - it is simply a complicated matter, and it is hard to communicate complicated issues, both when you don't know the terms to express them, or when your counterpart doesn't understand them. Think of it like a high school math problem: You won't ever find a solution to your trigonometry question (or get a decent answer), unless you learn some basic algebra first.
You also have a problem related to loading, application domains, and the Flash Player security model - which are all far more complicated than what you should aim at when trying out OOP stuff. This can be a major obstacle, and unless you want to frustrate yourself, you should try to avoid it, until your program actually runs.
So this here is my advice: Always try to solve one problem at a time. Do not work yourself into such complex scenarios as the one you are in right now, but take step by step, until you've reached a level where you are confident with what you are doing.
Your first issue should be to understand what's going on with classes and objects. Everything else will come later. You should try to isolate your problem in the pContent.swf and get that to work first - or better yet, put everything you need for your program into a single file. Convert to using classes. Then, once you know how to work with those, start learning about more advanced OO, decoupling your code using interfaces, type casting and loading binaries at runtime.
//makes contact with classs but comes out as: [object pContent]
its because you said
pContent = Content as Object;
I am not sure why you are doing this extra step
Change it to this
Content = TheContent.content as MovieClip;
// pContent = Content as Object; //NO NEED OF THIS
addChild(Content); // just in case this gives error change it as addChild(Content as Object);
var OSS:String = "device";
trace(Content); //now see the difference
Content.GetOnlineStatus(OSS); // it calls now
Also, give the link where you posted that scary question :P if it has rest of the code
Sorry if this does not sound like an answer, but I'm going to write a couple of doubts that I have reading your code that can possibly lead to the solution:
Why are you casting it to MovieClip? If you cast it as MovieClip, the compiler it is going to tell you that the method "GetOnlineStatus" doesn't exist, because MovieClip class doesn't have it! I think you have to cast it as pContent
Why are you trying to casting TheContent.content? What is "content"? I had a look to your previous post and I cannot see anything called "content"?
If I ignore my second doubt (TheContent.content issue), I would change the code like this:
Content = TheContent.content as pContent; // your class it's called pContent
addChild(Content);
Content.GetOnlineStatus(OSS); // it calls now
Also, keep in mind that generally it's a good pratice to capitalize name of classes and not variables.
Let me know!
private function GetOnlineStatus
Try making this a public function instead. When it's private it can't be accessed outside the scope of the class that owns it.
I believe that in order to make this work, content property of the Loader. You have to create a reference to the loaded SWF as the class you are trying to call. This class has to be included in the main SWF's project. Then you can call the functions of that particular class in the child.
function LoadContent()
{
TheContent.load(new URLRequest( "pContent.swf"));
TheContent.contentLoaderInfo.addEventListener(Event.COMPLETE, LoadContentTWO);
}
function LoadContentTWO(e:Event)
{
var pContent:GetOnlineStatus = GetOnlineStatus(e.target.content);
addChild(e.target.content); //Assuming that "TheContent was
// declared as var TheContent:Loader , you'd be adding the loader to the stage when I think you actually wanted // to add the content.
var OSS:String = "device";
trace(pContent); //// comes out as: [object pContent]
pContent.GetOnlineStatus(OSS); ///// HOW DO I GET THIS TO CALL FUNCTION
// This should work now. If not, try to loading a function that is not the class' main function. Because I think you might get an "unable to call static function error". I'm a begginner too though, so sorry if I'm wrong. Example: pContent.GetOnlineStatusFunction(OSS);
}
This answer assumes that the pContent.swf contains a class file that looks like this:
package {
public class GetOnlineStatus {
public function GetOnlineStatus (OSS:String) {
//Do your GetOnlineStatus Logic. This is the main function.
}
/*public function GetOnlineStatusFunction (OSS:String) {
//Example non-main function
} */
}
}
Source: http://www.scottgmorgan.com/accessing-document-class-of-externally-loaded-swf-with-as3/

keyboard input with actionscript

I'm writing in pure actionscript in notepad with flex as a compiler. Here's the code I have
package
{
import flash.display.*;
import mx.core.*;
import flash.events.*;
import mx.collections.*;
import flash.geom.*;
import mx.controls.*;
import flash.text.*;
import mx.events.*;
import mx.styles.*;
import mx.containers.*;
public class MAIN extends Sprite
{
public var APPLICATION:Application = Application(Application.application);
public var FRAME:int = 0;
public function MAIN()
{
addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
STEP();
}
public function STEP():void
{
FRAME ++;
STEP();
}
public function keyDownHandler(event:KeyboardEvent):void
{
var keyDownText:TextField = new TextField();
keyDownText.text = "Key code: " + event.keyCode;
this.addChild(keyDownText);
}
}
}
What I want is for whatever key I happen to press to be drawn on the screen (though actually I think it would only be the ascii number it corresponds to but that doesn't matter). Right now though everything's just blank. Another thing is because I'm not using any mxml I don't know if i've established the game loop correctly so let me know if that needs to be fixed.
Try
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
instead of
addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
Since your Sprite doesn't have a visible area, it will not receive keyboard or mouse input.
Also the STEP() function will cause a stackoverflow because it's infitely recursive.
If you want a main loop that gets called periodically, try using an ENTER_FRAME handler or a Timer.
Something like this:
public function MAIN()
{
addEventListener(KeyboardEvent.KEY_DOWN,keyDownHandler);
addEventListener(Event.ENTER_FRAME,STEP);
}
private function STEP(e:Event):void {
FRAME++;
}
To stop it, do this:
removeEventListener(Event.ENTER_FRAME,STEP);
Not sure why you are using ALL CAPS for some methods and variables. Although it's not a language requirement, all caps are generally reserved for constants. Method names use camelCase. And types use PascalCase (like camelCase, but the first letter is capitalized). So your class would be Main, FRAME would be fram, STEP would be step, etc. You're better off sticking to these common naming schemes, I think.
And another thing. You probably shouldn't be creating a new TextField instance everytime you want to output some text. One textfield will do it in your case, I think. So create and addChild the textfield on some kind of init method that you call when you start your class and then just use the text property of this textfield to write your messages.