Adobe Animate errors - actionscript-3

I'm trying to create a token that will disapear when the player touches it. I created an action for the token with the following code
package
{
import flash.display.MovieClip;
public class TokenFish extends MovieClip
{
public var isToken:Boolean;
public function TokenFish()
{
isToken = true;
}
}
}
However each time I try to run the scene to test it I will get the following errors.
Scene 1, Layer 'game_Stage', Frame 1, Line 5, Column 15 1131: Classes must not be nested.
Scene 1, Layer 'game_Stage', Frame 1 1159: The return statement cannot be used in package initialization code.
Any suggestions will very much be appreciated.

I figured it out. I was trying to create the class inside of an action which adobe animate doesn't allow. I had to create it as a separate actionscript file.

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.

MovieClip button In Class

Tried this,
package {
import flash.display.MovieClip;
import flash.events.*;
public class test extends MovieClip {
public function test() {
addEventListener(Event.ADDED_TO_STAGE, registerBtn);
}
private function registerBtn(e:Event):void {
this.parent["Homebtn"].addEventListener(MouseEvent.CLICK, myButtonClick);
}
private function myButtonClick(e:MouseEvent):void {
trace("CLICKED");
}
}
}
Image
And the same code on frame 1, And there's a MovieClip Button on stage having Instance name "Homebtn".
Imports
import flash.events.*;
Importing all classes from a package that originates in flash has zero impact on compile size because they're already present in the Flash Player runtime environment. It's pure monotony that you're required to explicitly declare these imports, but good practice when dealing with third party packages.
Stage Relationship
Document code (i.e., code in the Flash IDE timelines) have a direct relationship to MainTimeline, whereas class files do not. If you want to add button1.addEventListener(MouseEvent.CLICK, myButtonClick); to your class, you're not going to be able to do so unless you:
A: Pass a pointer to the button/stage/root to the class when instantiating your test class:
var myObj:test = new test(root)
B: Wait to add the event listener until after you've given the test object a parent relationship to the stage from which to traverse to the button:
addChild(test);
inside your class...
public function test() {
// constructor code
addEventListener(Event.ADDED_TO_STAGE, registerBtn)
}
private function registerBtn():void {
this.parent.button1.addEventListener(MouseEvent.CLICK, myButtonClick);
}
Turn on Debugging
To find the cause of your bugs, you need to debug your code. If you're using Flash IDE CS6, then you can enable this by going to your publish settings and enabling "Permit Debugging". This will take your ambiguous error...
null object reference at myDocument/doSomething()
...to a much clearer...
null object reference at myDocument/doSomething() package\myClass.as:20
...which now denotes which line in your code to look for your issue.
Use the Debug Console
Use the debugging compile mode to bring up the Debug Console. This will provide you with an immediate look at the line of code in question, as well as the Call Stack, and the state of all available Variables. No programmer should be without it.
Run by going to the menu "Debug > Debug Movie > Debug", or use the keyboard combo CONTROL+SHIFT+ENTER.
Now that you're armed with the know-how to do this on your own, I'll cover what you'd encounter, and how you'd fix it (since you're new).
First, it's flash.events with an "s". So we'll change that.
Next, compiling it we get the following errors:
So we see on line 7 of our test.as class: you've placed the timeline code into the class.
var myObj:test = new test(root);
addChild(test);
You don't want to instantiate you class from within itself as it'll never get instantiated. Think of your code as a railroad. The train starts with your timeline code, and only runs on the rails set before it. Your class is floating off to the side, ready with all its interesting turns and zigzags, but you have to add it to the rails for it to be actually run. That's instantiation; we're copying that path onto the current track, and the train runs on it.
So, we get rid of lines 6 & 7, and we're left with Access of possibly undefined property Homebtn. Calling this.parent is actually a getter function, and it returns a DisplayObjectContainer. Because AS3 is a strongly datatyped language, the compiler will know that there is no such property "Homebtn" on DisplayObjectContainers (silly compiler). But of course, you know it's there (or at least it will be by the time this code runs). A simple way of getting around that is by making it evaluate the reference at run-time.
this.parent["Homebtn"].addEventListener(MouseEvent.CLICK, myButtonClick);
By encapsulating the button name as a string and within brackets, we've done that.
Now we recompile again, and get the following:
This is because all event listeners receive one argument: an event object. You may not use it, but not having a variable to hold it is a no-no.
private function registerBtn(e:Event):void {
As a final point. All class functions need to be denoted as to what namespace they exist in. myButtonClick needs one, so we'll add it as private since no external (ie., non-class based) functions need access to it.
Here's your revised code:
test.as
package {
import flash.display.MovieClip;
import flash.events.*;
public class test extends MovieClip {
public function test() {
addEventListener(Event.ADDED_TO_STAGE, registerBtn);
}
private function registerBtn(e:Event):void {
this.parent["Homebtn"].addEventListener(MouseEvent.CLICK, myButtonClick);
}
private function myButtonClick(e:MouseEvent):void {
trace("CLICKED");
}
}
}
test.fla (timeline code on frame 1)
import test;
var Homebtn:MovieClip = new MovieClip();
Homebtn.graphics.beginFill(0xFF0000, 1);
Homebtn.graphics.drawRect(0, 0, 150, 25);
Homebtn.graphics.endFill();
addChild(Homebtn);
var testObj:test = new test();
addChild(testObj);

flash-as3 code execution order: accessing a flash pro instance after gotoAndStop()

this is a follow up question to this question
i have never actually got the flash-actionscript code execution order.
in flash pro i have an instance of a moveiclip on stage in frame one named tree1 and on frame 3 i have on the stage tree3.
in the document class i have this code:
stop();
var scaleFactor:Number = tree1.scaleX;
gotoAndStop(3);
tree3.scaleX = scaleFactor;
while this works when testing on the desktop, this app will go mobile at the end
is this the correct way to go or should i register for a frameComplete event before accessing instances on a certain frame
So, just dont use the Document Class cause you will need to declare all the scenes from the beginning and will be complicate to manage each scene.
I suggest you to instance a simple MovieClip linked with his own class like the example SceneTree, put it on each Keyframe. You will have more control when you are entering or exiting each frame.
package {
import flash.display.MovieClip;
import flash.events.Event;
public class SceneTree extends MovieClip {
public function SceneTree() {
super();
this.addEventListener(Event.ADDED_TO_STAGE, Init);
this.addEventListener(Event.REMOVED_FROM_STAGE, removed);
}
protected function Init (event:Event):void{
trace("added")
}
protected function removed (event:Event):void{
trace("removed")
}
}
}
waiting for Event.FRAME_CONSTRUCTED is the correct way whenever accessing assets on a timeline
it insures all assets have been created

How do I access the Document Class' properties from the time line in AS3?

I am building your standard slideshow flash header for a web page.
There are three main parts:
The Slideshow class
A controller class that is used as the projects Document Class
Some linking timeline code.
The slideshow class has all the functionality, so I used the Document class to create a new instance of the slideshow and keep a property variable called slideshow that keeps a reference the Slideshow instance.
import flash.display.MovieClip;
import flash.events.Event;
public class Header extends MovieClip
{
public var slideshow:Slideshow;
public function CSYC_Header()
{
var picturesURL:String = "images/pictures.xml";
var picturesURLFVar:String = root.loaderInfo.parameters.pictures;
picturesURL = picturesURLFVar ? picturesURLFVar : picturesURL;
slideshow = new Slideshow(picturesURL, Slideshow.FADE);
slideshow.init();
addChild(slideshow);
}
public function hello():void{trace("Hello");}
}
My next step now is to use Adobe Flash Professional to draw some play and stop buttons, and then link thier click events to call slidshow.play()/.pause(). This code is just place in the timeline:
import flash.events.MouseEvent;
pause_control_btn.addEventListener(MouseEvent.CLICK, pauseClicked);
play_control_btn.addEventListener(MouseEvent.CLICK, playClicked);
addChild(pause_control_btn);
addChild(play_control_btn);
function pauseClicked(e:MouseEvent):void
{
//the play and pause buttons are on the stage and have the following names as
// thier instance names: pause_control_btn, play_control_btn
pause_control_btn.alpha = 0;
play_control_btn.alpha = 0.37;
slideshow.pause();
}
function playClicked(e:MouseEvent):void
{
pause_control_btn.alpha = 0.37;
play_control_btn.alpha = 0;
slideshow.play();
}
Despite me being able to call regular methods that are in the Doc Class from the timeline, I can not call properties without the following error, for example when i say slideshow.play():
1061: Call to a possibly undefined method play through a reference with static type com.example.test:Slideshow.
So am I missing something obvious, or will I have to make a method on my document class every time I want to wire an event to call an object in my Document Class?
There's no need to put that code for the buttons on the timeline; you can reference those objects by their instance names from within the Document Class. That'd be the easiest solution, avoiding the timeline altogether, I think.
Otherwise possibly a call to parent.slideshow, or root.slideshow (though I think root is AS2, I don't quite remember) would give you access to that instance from the timeline. The former option is probably still the better option, and keeps your code in one place.
Hope that helps.