How do I use Actionscript "Classes" with a Flex MXML file? - actionscript-3

so far I've been completely stumped by this and I've been a few days at it, and most links I've followed and searches I've done have led me to nothing.
I want to make a simple game, with a mouse interface, but I also wanted to add a preloader. I was initially using minibuilder, as it is cross-platform and I am on Linux, but all the tutorials I saw to add a preloader seemed to be incompatible with it.
Thus I moved to just using the Flex compiler and a text-editor directly, but I haven't had much luck, and even the preloader (which seems to be the only think that actually works) is a mere copy from a tutorial that, by chance, worked.
Ideally, I'd want to merely use the MXML file to point to the preloader - having a CustomPreloader.as file for the preloader - and to start the Actionscript classes, possibly using FlashPunk along with my code to help.
This is code so far, for each of the files except CustomPreloader.as, as the preloader is already working: (Note: All files are in ~/ASClasses/src )
File: ASClasses.mxml
--------------------
<?xml version="1.0" encoding="utf-8"?>
<mx:Application
xmlns:mx="http://www.adobe.com/2006/mxml"
backgroundColor="#333333"
creationComplete="init();"
width="800" height="500"
frameRate="60"
preloader="CustomPreloader"
>
<mx:Script>
<![CDATA[
//This part is mostly for testing purposes
//========================================
import mx.controls.Alert;
public function init():void {
Alert.show("The first function works.");
}
//And this is what I actually wanted to do
//========================================
import Application;
//Whenever I uncomment the following line, some error is thrown and the init function stops working at all.
//public var myApp:Application = new Application;
//addChild(myApp);
]]>
</mx:Script>
</mx:Application>
File: Application.as
--------------------
package{
import flash.display.Shape;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.display.Sprite;
public class Application extends Sprite{
public function Application(){
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
stage.frameRate = 60;
rotationX = -45;
var s:Shape = new Shape;
s.x = 400;
s.y = 200;
s.rotation = 90;
addChild(s);
}
addEventListener('enterFrame', function(e:Event):void{
s.rotation += 2.5;
} );
}
}
However, uncommenting the line required to add Application.as seems to just throw an error, so I think that I am either missing some code or that I did something wrong.
Is there anyone who could teach me more about this, please? And although I'd like to say that I have some experience with Actionscript, at this point I've already stressed myself out so much about being unable to do this that I'd rather, if it's not too much to ask, be explained in a simple way, assuming I have no previous knowledge.
Additionally, if there are any full-blown simple tutorials for making a simple/simplistic game/demo this way, I'd appreciate that as well, as most tutorials I've seen so far only document Flex and Actionscript, and easily get complicated before I've actually managed to do anything.
Thanks in advance.
Edit 1: Also, it may be worth mentioning that the way it currently is it still manages to throw the Alert after loading.

Try
this.rawChildren.addChild(myApp);
Instead of
addChild(myApp);
Application extends Container, And When you add a child to Container, the child should implement the IUIComponent interface. Because the sprite class doesn't implements the interface, it will give you an error.
Here is some info about this Container addChild
EDIT
put the adding application code into a function,Like
public function init():void {
Alert.show("The first function works.");
var myApp:Application = new Application();
this.rawChildren.addChild(myApp);
}

Related

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

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.

Im trying to write a program which loads external resources with metadata tags in As3

ive been given some work to do but i cant seem to understand why its not working..
I think im using a wrong approach,
Im trying to load a picture and a movieclip on the same stage..
Though ive managed to display a picture, but when i try to display a MovieClip.. There arent errors though when i run i get the following:
TypeError: Error #1034: Type Coercion failed: cannot convert LoadingFiles_MovingStars1#2aba161 to flash.display.Bitmap. at LoadingFiles()[C:\Users\user\Adobe Flash Builder 4.5\LoadingFiles\src\LoadingFiles.as:28
Here is the code,
package
{
import flash.display.Sprite;
import flash.display.Bitmap;
import flash.display.MovieClip;
import flash.display.StageScaleMode;
[SWF(width = "800", height = "600", frameRate = "30", backgroundColor="#FFFF00")]
public class LoadingFiles extends Sprite
{
[Embed(source="/../assets/Head.jpg")]
protected var MovingStars:Class;
[Embed(source="/../assets/water1.mp4", mimeType = "application/octet-stream")]
public var MovingStars1:Class;
public function LoadingFiles()
{
stage.scaleMode = StageScaleMode.NO_SCALE;
// swf
var myStars:Bitmap = new MovingStars();
var myPic:Bitmap = new MovingStars1(); //
var yourPic:MovieClip = new MovingStars1();
myStars.x = (stage.stageWidth-myStars.width)/2;
myStars.y = (stage.stageHeight-myStars.height)/2;
addChild(myPic as MovieClip);
addChild(yourPic);
addChild(myStars);
}
}
}
Now ive written that code, but it doesnt work..
Im really stressing because im falling behind by a bit in class..
Help would greatly appreciated.
Thank you.
You're trying to instantiate an embedded .mp4 file as a Bitmap or a MovieClip. That's not possible, you need to create a video player or use an already existing videoplayer component.
Here's a more in-depth answer on that:
How to make an AS3 Flash video player?
When you embedded image
[Embed(source="/../assets/Head.jpg")]
protected var MovingStars:Class;
Your MovingStars is BitmapAsset class. This is class included in Flex SDK. So you need preload Flex SDK rsl's. Or configure Flex SDK libraries linking as merge in to code.
What IDE are you using?

How to convert a two-file preloader and game swf with Document class into single swf?

I have a game that I've made that runs in two files, one the preloader and one the swf. When I use these two files together they work fine, however some flash portals require only one SWF, so I'm trying to find the shortest-path way to convert it to use only one.
The game swf uses a Document Class that includes the package, class constructor, and tons of functions, and runs fine. I have lots of movieclips on the stage that I refer to in my code. The code is something like this (abridged):
package {
import flash.display.MovieClip;
import flash.events.MouseEvent;
...
public class Game extends MovieClip {
var EnemyArray:Array;
var HeroArray:Array;
...
public function Game() { // class constructor
EnemyArray = new Array();
addEventListener(Event.ENTER_FRAME,onEnterFrame);
mainRestartButton.addEventListener(MouseEvent.CLICK, RestartLevel);
...
}
public function KeyPressed(event:KeyboardEvent):void
{
if (event.keyCode == Keyboard.SPACE)
{
attack();
...
}
} // End of class
} // End of package
I also have another swf, my preloader, which has the following code in frame 1:
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.ProgressEvent;
import flash.events.Event;
var myLoader:Loader = new Loader();
myLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onLoading);
var myURL:URLRequest = new URLRequest("Game.swf");
myLoader.load(myURL);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onComplete);
function onLoading(event:ProgressEvent):void {
var loaded:Number = event.bytesLoaded / event.bytesTotal;
percent_txt.text = "Loading: " + (loaded*100).toFixed(0) + "%";
}
function onComplete(event:Event):void {
myLoader.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onLoading);
myLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onComplete);
this.addChild(myLoader);
}
I've been through the gamut of solutions online and none of them seem to work with the way that my code is set up, such as: How to create Preloader in AS3
I tried his option 1 by taking all the code in my Document Class other than the package and constructor and pasted it into frame 2. However it returns "Error #1009: Cannot access a property or method of a null object reference." for any references to items on the stage, such as:
mainRestartButton.addEventListener(MouseEvent.CLICK, RestartLevel);
As he mentions, "This works well if you organized your project in a way that the most of the assets (images, etc) are in the Flash IDE Library and are not loaded on the first frame (you can check that in each library item's properties)." My project is NOT organized in such a way.
What is the easiest way for me to reorganize my FLA/code so they can have a preloader in a single swf?
Thanks so much for your time and help!
I use FlashDevelop (no FLAs) so I'm not sure if it'll work for you but I use the solution described here.

Away3D Context3D not available

I'm checking out Flash's 3D capabilities with Away3D, and I'm following the tutorial here. I've run into a major problem though. Everytime I run my project in the browser, I get this error:
Error #2044: Unhandled ErrorEvent:. text=Error #3702: Context3D not available.
I can't see where this error comes from, but it happens after my constructor function ends and before the ENTER_FRAME handler starts.
My code is like this:
package {
import away3d.containers.View3D;
import away3d.entities.Mesh;
import away3d.materials.ColorMaterial;
import away3d.primitives.SphereGeometry;
import flash.display.Sprite;
import flash.events.Event;
[SWF(backgroundColor="#000000", frameRate="60", width="1024", height="768")]
public class TestAway extends Sprite {
private var view:View3D;
public function TestAway() {
view=new View3D();
addChild(view);
var sphereGeometry:SphereGeometry=new SphereGeometry(350);
var sphereMaterial:ColorMaterial=new ColorMaterial(0xff0000);
var mesh:Mesh=new Mesh(sphereGeometry, sphereMaterial);
view.scene.addChild(mesh);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(event:Event):void {
view.render();
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}
}
}
Now the wierd thing is, when I run it on my browser (FP 11.2), it doesn't work (gives that error), but I can run the swf from the desktop perfectly.
Also, the example file on the tutorial page runs perfectly. What setting is missing, and how can I fix it?
Well, it appears you need to set wmode as direct to make use of the 3D API.
While I had seen this bit of info, the html wrapper needs to be modified in 3 places for it to work on all configurations:
(1) In the javascript for swfObject
params.wmode = "direct";
(2) In the <object> tag
<param name="wmode" value="direct" />
and (3) in the <object> tag for IE
<param name="wmode" value="direct" />
To extend further helpful hints, if you are trying to open an application that uses Context3D in a new NativeWindow, you need to make sure that the you specify the renderMode in the NativeWindowInitOptions that gets passed into the NativeWindow. The render mode cannot change after the Native Window gets created.
// New window.
options = new NativeWindowInitOptions();
options.renderMode = "direct";
options.transparent = true;
options.systemChrome = NativeWindowSystemChrome.NONE;
nativeWindow = new NativeWindow( options );
I'm posting here hoping to help anyone with the same problem, but exporting to AIR.
Edit the app descriptor.xml and change the value to of rendermode to:
<renderMode>direct</renderMode>
Hope it helps

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/