Possible to have multiple timelines? (separate part without affecting the keyframes of other layers) AS3 - actionscript-3

http://i.snag.gy/eu7iz.jpg
So im doing this generator/designer on flash. It has different features on it so the keyframes clashes with other features considering a lot of the action scripts deal with nextframes and gotos. Its getting confusing once i add little features.
Like right now i wanna add next buttons for the design part. I can do it easily with a blank stage, i can easily click next and back, but when applied to my project, its getting a little dizzying.
This is the script for the first frame:
stop();
small.addEventListener(MouseEvent.CLICK,play1);
function play1(event:MouseEvent):void{
gotoAndStop("3");
}
medium.addEventListener(MouseEvent.CLICK,play2);
function play2(event:MouseEvent):void{
gotoAndStop("6");
}
large.addEventListener(MouseEvent.CLICK,play3);
function play3(event:MouseEvent):void{
gotoAndStop("8");
}
item_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragTheObject);
item_mc.addEventListener (MouseEvent.MOUSE_UP, itemRelease);
item_mc1.addEventListener(MouseEvent.MOUSE_DOWN, dragTheObject);
item_mc1.addEventListener (MouseEvent.MOUSE_UP, itemRelease);
item_mc2.addEventListener(MouseEvent.MOUSE_DOWN, dragTheObject);
item_mc2.addEventListener (MouseEvent.MOUSE_UP, itemRelease);
function dragTheObject(event:MouseEvent):void {
var item:MovieClip=MovieClip(event.target);
item.startDrag();
var topPos:uint=this.numChildren-1;
this.setChildIndex(item, topPos);
}
function itemRelease(event:MouseEvent):void {
var thisItem:MovieClip=MovieClip(event.target);
thisItem.stopDrag();
};
This is the fla file: https://www.dropbox.com/s/77euop1luqjreos/FINAL.fla

MovieClips have their own timeline.You may want to modularize your program into Movieclip components and export for Actionscript manipulation that you can instantiate at run time as necessary. Now that is one way to do it to avoid code spread across one single timeline.But If you still want to stick to your way (use of single timeline), You still could achieve your next/previous implementation without affecting frame logic at any rate.A simple way to do this goes like this:
Encapsulate all logic into functions and put these functions solely on frame 1 and nothing else.
This keeps logic clean and separate from the components.Also, the logic layer in principal should not have nothing else.Why on Frame 1?. Well, we want to expose and keep in memory first the logic, so that whatever component related code that follows on the subsequent frames should be aware of the previous logic and hence throw no run time errors when interacting frame 1 logic.
Spread your components and related code across the subsequent frames respectively.
Put only component related code on a frame that has the component in question. registering event listeners could have targets as their dependency. define event listeners and put them on frame 1 as part of the logic and simply put code for registering listeners on the component frames as per demand.
Example:
//On Frame 1
function onAMouseClick(event:Event):void
{
//implement logic
}
function onBMouseClick(event:Event):void
{
//implement logic
}
//Implemented function for next/back buttons
//Also on Frame 1
function navigate(event:Event):void
{
var frame:int;
switch(event.target.name)
{
case "nextBtn":
frame=currenFrame<numFrames?+1:numFrames;
gotoAndStop(frame);
break;
case "backBtn":
frame=currenFrame>2?-1:currentFrame;
gotoAndStop(frame);
break;
}
}
//On Frame 2 for A component
A.addEventListener(MouseEvent.CLICK, onAMouseClick)
//On Frame 3 for B component
B.addEventListener(MouseEvent.CLICK, onAMouseClick)
Put Next/Back button components on a single layer spreading from frame 2 all the way to the end of the last frame where you want the buttons to be visible. Then implement related code having its visibility spanning across between frame 2 and the last frame as the following shows:
//navigate handler is declared and implemented on **frame 1**
nextBtn.addEventListener(MouseEvent.Click, navigate)
nextBtn.addEventListener(MouseEvent.Click, navigate)
Well, that is your way of doing things (Single timeline scripting). Not bad for simple timeline scripting.You may try the other way also of instantiating Movieclips (exported for action scripiting)
at run time and the add these to the display list as per demand as on clicks next/back buttons.In doing so you will not only have one single point of logic but will have MC code encapsulated in each individual component.
Hope the foregoing helps. Thanks.

Do not be scared to change code! Let alone afraid to run into errors! That's way forward you want to learn to fix things that's a beauty of it!
.....cheers!.

Related

Check the existence of an object instance

I'm surprised I don't know how to do this, but as it turns out I really don't; simply put, I'm trying to make a side-scrolling shooter game, a basic one and in it, I have 50 stars spawned on-screen through a "for" loop upon the game starting. There is a function which does this and a listener is at the beginning. Problem is, when you lose the game and go back to main menu, 50 more stars would be spawned, which isn't what I want. So, I'm trying to make an "if" statement check at the beginning, so that the game checks whether there is an instance/movie clip of the star object/symbol before determining whether the function that spawns stars should be called out with a listener. So, how do I do this? I looked through some other checks and they didn't help as the codes presented were vastly different there and so I'm just getting errors.
Let me know if a better explanation is needed or if you would like to see some of the code. Note that the game overall already has a lot of code, so just giving all of it would probably not be helpful.
I suggest you rethink your approach. You're focusing on whether stars have been instantiated. That's ok but not the most basic way to think about it.
I would do this instead
private function setup():void{
loadLevel(1);
addListeners();
loadMusic();
// etc...
// call all functions that are needed to just get the app up and running
}
private function loadLevel(lev:int):void{
addStars();
// call all functions that are needed each time a new level is loaded
}
private function restartLevel():void{
// logic for restarting level,
// but this *won't* include adding star
// because they are already added
}
There are other ways to do this but this makes more sense to me than your approach. I always break my game functions into smaller bits of logic so they can be reused more easily. Your main workhorse functions should (IMHO) primarily (if not exclusively) just call other functions. Then those functions do the work. By doing it this way, you can make a function like resetLevel by assembling all the smaller functions that apply, while excluding the part about adding stars.
Here's what I did to solve my problem... Here's what I had before:
function startGame():void
{
starsSpawn();
//other code here
}
This is what I changed it to:
starsSpawn();
function startGame():void
{
//other code here
}
when you said existance, so there is a container, i named this container, (which contain stars , and stars was added to it) as starsRoot, which absolutely is a DisplayObject (right?)
now, to checking whole childrens of a DisplayObject, we have to do this :
for (var i:int=0; i<starsRoot.numChildren; i++) {
var child = starsRoot.getChildAt[i];
}
then, how to check if that child is really star!?
as you said
whether there is an instance/movie clip of the star
so your stars's type is MovieClip, and they don't have any identifier (name), so how to find them and make them clear from other existing movieclips. my suggestion :
define a Linkage name for stars from library, thats a Class name and should be started with a capital letter, for example Stars
now, back to the code, this time we can check if child is an instance of Stars
for (var i:int=0; i<starsRoot.numChildren; i++) {
var child = starsRoot.getChildAt[i];
if (child is Stars) {
// test passed, star exist
break;
}
}

AS3 Change Frame/Instance within MovieClip

I am not a programmer, so please forgive me if my question is too noobish.
I created a MovieClip in my library called "skill". Then I added three instances of that MovieClip into my stage called "skill_01", "skill_02", and "skill_03" respectively. I selected all three instances and created another MovieClip called "diagram" to nest them inside it. I will later add more skill instances inside this MovieClip called "diagram" but for now, I need the basics to work with three instances.
The main timeline or stage only has 1 frame, and so does the "diagram" MovieClip instance. However, the skill instances all have two frames: in frame 1 I have an PNG image showing them as being locked/offline, and in frame 2 I have another PNG showing them as unlocked/online. I need to be able to toggle them by clicking and right clicking on them, just like in the example below (see link)
I am trying to make it so that when you left click the skill instances they toggle to Online/Unlocked by switching to the PNG image in frame 2, and when you right click them, it goes back to frame 1 (Offline/Locked). I've tried several different lines of code, including the ones recommended by Adobe itself, and others, and I can't figure out what I'm doing wrong. It will go to frame 2 and refuse to go back to frame 1 when right clicked.
This is the code I have in the MovieClip:
stop();
skill_01.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextFrame);
function fl_ClickToGoToNextFrame(event:MouseEvent):void
{
gotoAndStop(2);
}
This part of the code doesn't work:
skill_01a.addEventListener(MouseEvent.RIGHT_CLICK, fl_ClickToGoToPreviousFrame);
function fl_ClickToGoToPreviousFrame(event:MouseEvent):void
{
prevFrame();
}
Screenshot 1:
gyazo (dot) com/e622baee46c3fabbd8c9a8d2df8396fe
Screenshot 2:
gyazo (dot) com/1b360716a5d243aa74e2be4127fe9a5b
(Sorry for typing the links like that, it won't let me add more than 1 link because I just signed up to this Forum)
For more context, I am trying to make a Skill Tree, that works similar to this one: http://www.dungeonsanddevelopers.com/#__6_Your
I will appreciate any help figuring this out!
if you have named your movieclip, skill_01, so what is the skill_01a ?
also add your event listener and its callback function in to the movieclip's parent and inside the callback function, for accessing the event owner, use
// stop(); not necessary to call stop if you have only 1 frame
with (this.diagram) {
skill_01.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextFrame);
skill_02.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextFrame);
skill_03.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextFrame);
skill_04.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextFrame);
skill_01.gotoAndStop(1);
skill_02.gotoAndStop(1);
skill_03.gotoAndStop(1);
skill_04.gotoAndStop(1);
}
function fl_ClickToGoToNextFrame(event:MouseEvent):void
{
if (MovieClip(event.target.parent).currentFrame == 1)
MovieClip(event.target.parent).gotoAndStop(2);
else
MovieClip(event.target.parent).gotoAndStop(1);
}
Edit: when an event is dispatched from clicked movieclip, only the last movieclip inside hierarchy tree will be passed as event.target in your exaple, that can be skill_01 (if currentframe is 1) or skill_1a (if currentframe is 2) athwart the question body, you have not only a png image inside skill's frame 1 and 2, they are movieclip's and will be returned as event.target. but if you only put your bitmaps (locked.png & unlocked.png) instead of skill_01 and skill_01a, the previous code works fine. bitmaps does not capture event so its parent is who accepted click event and its all a little confusing, i'm not good at explain
if its hard to comprehend
we shall use some thing like it, easier but larger code
with (this.diagram) {
skill_01.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextFrame_s1);
skill_02.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextFrame_s2);
skill_03.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextFrame_s3);
skill_04.addEventListener(MouseEvent.CLICK, fl_ClickToGoToNextFrame_s4);
skill_01.gotoAndStop(1);
skill_02.gotoAndStop(1);
skill_03.gotoAndStop(1);
skill_04.gotoAndStop(1);
}
function fl_ClickToGoToNextFrame_s1(event:MouseEvent):void {
toggle_buttons(skill_01);
}
function fl_ClickToGoToNextFrame_s2(event:MouseEvent):void {
toggle_buttons(skill_02);
}
function fl_ClickToGoToNextFrame_s3(event:MouseEvent):void {
toggle_buttons(skill_03);
}
function fl_ClickToGoToNextFrame_s4(event:MouseEvent):void {
toggle_buttons(skill_04);
}
function toggle_buttons(button:MovieClip):void
{
if (button.currentFrame == 1)
button.gotoAndStop(2);
else
button.gotoAndStop(1);
}

Saving the state of a movieclip containing multiple movieclips inside

this is actually a noobish question, but is there a possible way to save a certain state of a movieclip?, example i dynamically added a movieclip called big_mc, then inside big_mc contains three(3) smaller movie called child_mc1 and child_mc2 and a close_big to remove big_mc from the stage, when i click either of child_mc1 and child_mc2, the child_mc will disappear prior to which child_mc i clicked.
so the scenario is when I click child_mc1 which remove itself from the scene, then next I'll click the close_big movieclip to remove big_mc from the stage and will save it's own state, so then the next time i run the SWF file and dynamically add big_mc to stage, child_mc1 would be still missing and child_mc2 would still be displayed (EVEN IF I CLOSE THE SWF FILE, the state should be saved). please help..much is appreciated.
code in main time line:
var big_mc:mother_mc = new mother_mc;
add_big_btn.addEventListener(MouseEvent.CLICK, call_big);
function call_big(e:MouseEvent):void
{
addChild(big_mc);
}
the code inside big_mc:
child_mc1.addEventListener(MouseEvent.CLICK, remove_child1);
child_mc2.addEventListener(MouseEvent.CLICK, remove_child2);
close_big.addEventListener(MouseEvent.CLICK, bye);
function remove_child1(e:MouseEvent):void
{
removeChild(child_mc1);
}
function remove_child2(e:MouseEvent):void
{
removeChild(child_mc2);
}
function bye(e:MouseEvent):void
{
this.parent.removeChild(this);
}
You want to start with SharedObject, which as Adobe puts it, "is used to read and store limited amounts of data on a user's computer or on a server". To save the "state" of the MovieClip is more complicated.
What about it do you want to save? The x property? Perhaps the alpha? EVERYTHING? Each object is stored in a default state in your swf. Library items in the Flash IDE are technically miniature classes, as evidenced by the way we instantiate them. Assuming you create something called customButton, you could spawn thousands of them onscreen (or one) like this:
var foo:customButton = new customButton();
Like a hand-written class, a copy of the customButton is created with all the properties you defined on it before you compiled it. If you want to change those properties, you have to address each and every one you want different.
Looking at this broadly, let's assuming you want to save the position of your button every time you load the swf. Load with getLocal(), and save with flush().
var settings:Object = SharedObject.getLocal("foo");
function updateState(e:Event):void {
myButton.x = settings.x;
myButton.y = settings.y;
}
function saveState():void {
settings.x = myButton.x;
settings.y = myButton.y;
settings.flush();
}
It's not impossible; there's simply no push-button solution for it. If you wanted, you could write a function which iterates over all DisplayObjects, and loads/saves each relavent property from/into your SharedObject. Might be overkill, though.

Tweening with actionscript 3

I have been working on this one a while. I have an object in this case a movieClip called "mcBall". I set up two buttons "btnLeft" and "btnRight"with a tween so that the mcBall will ease between the two points smoothly.
Works fine, but where it gets glitchy is the the two buttons are still active an if the user clicks on either button of course the ball goes back to the starting point like it's supposed to.
My question is this ... What is the best way to have the buttons be de-activated while the "mcBall" object is moving. Would it be best to use a removeEventListener for the buttons and then have it added again. Would it be better to use an if statement like "If (mcBall.x = >=81 || <=469) removeEventListener"? Maybe use the tweenEvent.MOTION_FINISH to set up the eventListener again.
Any help would be greatly appreciated. Thanks
using Flash cs3
In this code I managed to turn off one button so that while the ball is moving it remains inactive but the other is still active. I'm not sure of the placement of the removeEventListener.
import fl.transitions.Tween;
import fl.transitions.easing.*;
function moveBallRight(evt:MouseEvent):void {
var moveBall:Tween=new Tween(mcBall,"x",Regular.easeOut,80,470,4,true);
btnRight.removeEventListener(MouseEvent.CLICK,moveBallRight);
btnLeft.addEventListener(MouseEvent.CLICK,moveBallLeft);
}
btnRight.addEventListener(MouseEvent.CLICK,moveBallRight);
function moveBallLeft(evt:MouseEvent) {
var moveBall:Tween=new Tween(mcBall,"x",Regular.easeOut,470,80,4,true);
btnRight.addEventListener(MouseEvent.CLICK,moveBallRight);
btnLeft.removeEventListener(MouseEvent.CLICK,moveBallLeft);
}
btnLeft.addEventListener(MouseEvent.CLICK,moveBallLeft);
Personally, I would recommend using the Actuate tween library. Unlike TweenLite/Max, it is fully opensource, and has most of the features, and is faster, with no pro/pay version.
I also like Actuate's interface much better than TweenLite. It is very similar so easy for people to start using it, but I like how tween modifiers are added in a more explicit way.
Simple example:
Actuate.tween(mySprite, 1, { alpha:1 });
Then is you want to specify an easing equation, just chain it on the end:
Actuate.tween(mySprite, 1, { alpha:1 }).ease(Quad.easeOut);
Want a delay as well? Add that to the chain:
Actuate.tween(mySprite, 1, { alpha:1 }).delay(1).ease(Quad.easeOut);
Of course you can also call a function onComplete, even with parameters:
Actuate.tween(mySprite, 1, { alpha:1 }).onComplete(trace, 'Tween finished');
Check out the Actuate Google Code page linked above for the full list of methods with examples.
I would recommend not using the native Tween class from fl.transitions.Tween. Its not very good. The industry standard is TweenMax from greensock.
Using TweenMax it is trivially easy to respond to end-of-tween events. You simply add an onComplete:myhandlerfunction to your tween.
An example from your above code would look like this:
Instead of
var moveBall:Tween=new Tween(mcBall,"x",Regular.easeOut,80,470,4,true);
You would have:
TweenMax.to(mcBall, 4, {x:470, ease:Expo.easeOut, onComplete:onBallMovedLeftComplete};
Hope that helps. And I hope you never have to use those native tween classes again. They are the pits.
I agree that you should use TweenLite or TweenMax as the other answers suggests.
From what I gather though, the question is the best approach in activating/deactivating your event listeners for the buttons.
I'd say the best approach is to have a function for adding your button listeners and another function for removing them.
Then, whenever you call a tween, you first call the removal function before executing the tween.
Then upon completion, you call the function to add them again. You can use the onComplete parameter with Tweenlite to specify the function to add the button listeners.
for example :
function moveBallRight(evt:MouseEvent):void
{
removeButtonListeners();
TweenLite.to(mcBall, 4, {x:470, ease:Expo.easeOut, onComplete:addButtonListeners};
}
function moveBallLeft(evt:MouseEvent):void
{
removeButtonListeners();
// do your tween
TweenLite.to(mcBall, 4, {x:80, ease:Expo.easeOut, onComplete:addButtonListeners};
}
function addButtonListeners():void
{
// add both listeners here
}
function removebuttonListeners():void
{
// remove both listeners here
}
Also, you'd obviously want to call addButtonListeners at the beginning of your program as well, so that the listeners are initially active when the program runs.

Game logic and game loops in ActionScript 3

I am making a Shooting game in flash actionscript 3 and have some questions about the flow of logic and how to smartly use the OOPs concepts.
There are mainly 3 classes:
Main Class: Initializes the objects on the screen.
Enemy Class: For moving the enemies around on the screen.
Bullet Class: For shooting.
What I want to do is find out if the Enemy has been hit by a bullet and do things which must be done as a result ...
What I am doing right now is that I have a ENTER_FRAME event in which i check collision detection of each enemy unit (saved in an array) with the bullet instance created, and if it collides then perform all the necessary actions in the Main class .. clogging the Main class in the process ..
Is this the right technique ? or are there better solutions possible ?
Try to think more OOP, what is every object responsible for?
We have the enemies wich we can hit:
class Enemy : extends NPC implements IHittable {
. . .
function update(delta) {
// move, shoot, etc.
}
function handleHit(bullet) {
// die
}
}
A hittable object:
interface IHittable {
function handleHit(bullet);
}
The bullet is suppose to move and hit things:
class Bullet : {
function update(delta) {
// update position
}
function checkHits(world:World) {
for each(var hittable:IHittable in world.objects) { // might want to cluster objects by location if you're handling lots of objects / bullets)
if (isColidingWith(hittable))
o.handleHit(bullet);
}
}
}
And then we have the world with everything inside:
class World {
var npcs: Array ...
var bullets: Array ...
var hittables: Array ...
function update(delta) {
foreach(var c:NPC in npcs)
c.update(delta);
foreach(var b:Bullet in bullets) {
b.update(delta);
b.checkCollisions(world);
}
}
}
And your main loop is just simple as that:
var lastTime:int;
function onEnterFrame(...) {
var now:int = getTimer(); // FlashPlayer utility function to get the time since start (in ms)
world.update(now - lastTime);
lastTime = now;
}
A few other notes:
try to do all the computation based on a delta of time, otherwise the game's speed will vary with the framefrate.
what happens when a character dies? bullet disappear? Well, you could do it several ways:
fire an event, like EnemyDied and remove it from the world
implement an interface CanDie that has a (get dead():Boolean property) and use that to cleanup the world at every update.
but don't write the code to remove the enemy in the Enemy class, because then you will be polluting the class with code that should be handled by the World, and that will be hard to maintain later.
Sorry for the long answer, but I couldn't help myself :)
Was clogging the Main class the problem, or finding out what bullet hit what enemy the problem? If it was the bullet, you need to describe the bullet behavior - can it hit multiple enemies, how fast does it move (is it possible that when testing using "enterFrame" the bullet will first appear in front of the enemy, and, on the second frame, it will appear behind the enemy?). May enemy be simplified to some basic geometrical shape like circle or rectangle, or do you need pixel-perfect precision? Finally, how many bullets and how many enemies are you planning to have at any one time? It could be too expensive to have a display object per bullet, if you are going to have hundreds of them, and then it could make more sense to draw them into single shape / bitmapdata.
If the problem is that the Main class is too long, there are several possibilities here.
A nobrainer answer to this problem - use inheritance to simply put parts of the code in separate files. Not the best way, but a lot of people do it.
If you did the first, then you'd realize that there are certain groups of functions you put into superclass and subclasses - this will help you split the "clogged" class into several smaller independent pieces that have more particular specialization.
After you did the second, you may find out that there is certain dependency between how you split the big class into smaller classes, so you can try generating those smaller classes by a certain pattern.
And then you write the clogged code that generalizes those parts you just managed to split.
Above is basically the cycle from more concrete to more generic code. In the process of perfecting the last step, you'll write some concrete code again. And that will move you to the step 1. Lather, rinse, repeat :) In fact, you don't want to write OO code, or procedure code or anything that fashion of the day tells you to do. You want to write good code :) And you do it by moving from more generic to more specific and back to more generic, until it's perfect :P
Probably not the best answer, but you must admit, you didn't give much info to give you more precise answer.