How to use a single script for multiple frames - actionscript-3

I've build a topotrainer in Flash consisting of 50 states.
For every state I made a frame. The code of these 50 frames should be the same for all, while the graphics defer. If I put the code on the first of the 50 frames it is only working there. If I put the code at every frame I get a lot of errors, because all the functions are doublated.
Is there a way for all the 52 frames to run the same code?
Thanks for your time,
More info:
The red square is indicating the 50 states. That is pure graphicly.
I made a seperate layer for all the coding.
The blue circle indicates the (working) code for one single state-frame.
All the 50 graphical frames want to use this code.
#Atriace: is your explanation solving this particular problem?
Thanks,
Justin

Update
The important thing to be aware with frames is that things don't exist until after they're initialized. Assume that on Frame1 we have the blue square, and on Frame2 we have the red circle.
The play-head starts on the left and works its way to the right. As it arrives at each frame, it then creates whatever it finds there for it, be it a symbol or code. This means that if we try to hook up the red circle with an event listener on Frame1 it will fail; naturally because red circle hasn't been created yet.
stop();
function hello(e:Event):void {
var destination:int = (currentFrame == 1) ? 2 : 1;
trace("Hello " + e.currentTarget.name + ": " + currentFrame + " of " + totalFrames + " > " + destination)
gotoAndStop(destination)
}
BlueSquare.addEventListener("click", hello);
RedCircle.addEventListener("click", hello); // <<< this will fail
However, if we put that single line on the same frame as when the red circle is created, it will link to hello() correctly and run.

Related

Jumping back and forth inside a Movieclip with a button?

So, I'm very much a beginner in AS3. I've been reading and figuring out things as I go, though I can't wrap my head around this.
So, I have 4 frames. Each frame has a different movie clip, MC1,MC2,MC3,MC4
Inside those four movie clips, there is another movie clip with the same instance name for each: BC, and inside that movie clip there are two frames. Frame 1 has a dot, and frame 2 does not.
MC1>BC>(2 frames)
MC2>BC>(2 frames)
and so on....
What I'm trying to do: I wanted to see if there was any way to control the frame navigation of BC inside all four MC clips at the same time with one button.
I want to switch back and fourth between the two frames inside the BC movie clip.
I'm at a loss, I've tried quite a few things.
You should be able to do so by giving them all the same instance name (so long as there is only ever one of them on screen at once).
So lets say you have a button that spans all 4 frames with an instance name of navBtn and you gave each of the MC1-4 clips the same instance name of MC. You could do the following on frame 1:
navBtn.addEventListener(MouseEvent.CLICK, navBtnClick);
function navBtnClick(e:Event):void {
if(MC.BC.currentFrame == 2){
MC.BC.gotoAndStop(1);
}else{
MC.BC.gotoAndStop(2);
}
}
Reading your question again, perhaps what are looking for is to have each clip automatically go to the same frame for their BC child when they load? If that is the case, then follow the example in the comment on your question by #Organis. Here is one way you could accomplish this:
Create two variable on frame one of your main timeline:
var BC_NAV_CHANGE:String = "BC_NAV_CHANGE";
var BC_CurFrame:int = 1;
Then, when you need to change the frame of the BC objects, do the following:
//create a function that you call when you want to change the BC frame
function toggleBCFrame(e:Event = null){
MovieClip(root).BC_CurFrame = MovieClip(root).BC_CurFrame == 1 ? 2 : 1;
//the line above is a if/else shorthand, that is setting a new value to the `BC_CurFrame` var,
//if the current value is `1`, it will set it to `2`, otherwise it will set it to `1`
MovieClip(root).dispatchEvent(new Event(MovieClip(root).BC_NAV_CHANGE));
//this line (above) dispatches a event telling anything that's listening that the variable has changed
}
If the code above is on the main timeline, you can forgo all the MovieClip(root). parts of the code.
Now, on the timeline of your BC MovieClip(s), put the following code:
//create a function that goes to and stops at the frame stored in the global variable
function updateFrame(e:Event = null){
gotoAndStop(MovieClip(root).BC_CurFrame);
}
//next listen for the BC_NAV_CHANGE event, and call the above update function above any time that event happens
MovieClip(root).addEventListener(MovieClip(root).BC_NAV_CHANGE, updateFrame);
//lastly, call the update function right away so when the BC clips loads it immediately goes to the correct frame
updateFrame();

Keeping the current CCSprite to another scenes

I'm a beginner of using cocos2d-x.
My problem is I dun know how to keep the CCSprite to another scenes.
The details of my case:
I've made a class"Scene01"includes 5 characters CCSprite with attributes, each of them class name like C1,C2...C5.
I've made a "Draw" button at class"Scene02"to draw out 1 of them randomly. I put this action at "CCTouchesBegan"...the character draw setting as below:
if (probability >0 && probability <=20) {result = C1::create();}
else if (probability >20 && probability <=40){result = C2::create();}
...until C5::create();
I use "this->addChild(result);" display on "Scene02" at "CCTouchesBegan".
But I don't know how to keep the generated "result(CCSprite)" to the new scene class"Scene03". Is there any better way(s) to simplify my case or any method(s) can help me to complete it?
You could try the following: retain the Sprite, remove it from Scene02 (keeping it on the heap) and then add it to the Scene03.
//(Scene02)
result->retain();
result->removeFromParent();
..
//(Scene03)
this->addChild(result);
result->release();

Trigger a function when specific frame number is reached - AS3

I wanted friends, do the following when my MC get a determanido internal quandro, it triggers a function to another MC. for example when the ball hit the wall, a person goes to search - la, I have tried using :
("root") {root.MC.play ()}
Translation from comments:
Friends, I have an MC_1 with 10 frames, when it reaches frame 5, I want another movieClip MC_2 to respond (eg: to move or fade etc)
creating a ENTER_FRAME listener for your MC_1 is the easiest way to achieve this
MC_1.addEventListener(Event.ENTER_FRAME,respond);
function respond(e:Event):void{
if(MC_1.currentFrame>=5)
MC_2.gotoAndPlay(2);
//or any other respose you want from MC_2
}
addFrameScript can be used in AS3 to specify a function to execute on reaching a MovieClip frame.
MovieClip.addFrameScript(index:int, func:Function);
A sample implementation of this:
// addFrameScript's index is zero Based, hence 4 means frame 5
MC_1.addFrameScript(4, funcToExecute);
function funcToExecute():void{
// this will get called when MC_1 reaches frame 5
// do stuff here, like manipulating MC_2, etc...
}

Actionscript 3- Random movement on stage? Also, Boundaries?

I'm trying to code something where there are creatures running back and forth, up and down across the stage, and I the player, have to try to go up to them, and pick them up. There are also boundaries on stage-
The map constraints- a big rectangle box is easy enough to accomplish. I've done this.
The boundaries within the map, which are also rectangles, but instead of bouncing the player back INSIDE the rectangle, I'm trying to do the opposite- keep the player out of it.
My code for it looks like this as of now:
//Conditions that check if player/monsters are hittesting the boxes (rocks
//and stuff), then if correct, bounce them away. Following code excludes
//the monsters for simplicity.
if((mcPlayer.x - aBounceBox[b].x) < 0 && mcPlayer.y <= (aBounceBox[b].y + aBounceBox[b].height/2) && mcPlayer.y >= (aBounceBox[b].y - aBounceBox[b].height/2))
{
mcPlayer.x = aBounceBox[b].x - aBounceBox[b].width/2 - mcPlayer.width/2;
}
//Duplicate above code for right side of box here
if((mcPlayer.y - (aBounceBox[b].y + aBounceBox[b].height/2)) < 0 && (mcPlayer.x + mcPlayer.width/2) > (aBounceBox[b].x - aBounceBox[b].width/2) && (mcPlayer.x - mcPlayer.width/2) < (aBounceBox[b].x + aBounceBox[b].width/2))
{
mcPlayer.y = aBounceBox[b].y + aBounceBox[b].height/2;
}
//Duplicate above code for Upper boundary of box here
The above doesn't work very well because the code to bounce for the left and right sides of the box conflicts with the upper and lower parts of the box I'm hit-testing for. Any ideas how to do that smoothly?
Also, another problem I am having is the pathing for the monsters in the game. I'm trying to get them to do the following:
Move around "organically", or a little randomly- move a little, stop. If they encounter a boundary, they'd stop and move, elsewhere. Not concerned where to, as long as they stop moving into rocks and trees, things like that.
Not overlap as much as possible as the move around on stage.
To push each other apart if they are overlapping, although I'd like to allow them to overlap very slightly.
I'm building that code slowly, but I thought I'd just ask if anyone has any ideas on how to do that.
To answer your first question, you may try to implement a new class/object which indicates the xy-offset between two display objects. In order to illustrate the idea more clearly, you can have a function similar to this:
public function getOffset(source:DisplayObject, target:DisplayObject):Object {
var dx:Number = target.x - source.x;
var dy:Number = target.y - source.y;
return { x:dx, y:dy };
}
Check if the hero character is colliding with another object first by hitTestObject(displayObj) of DisplayObject class. Proceed if the result is true.
Suppose you pass in your hero character as the source object, and another obstacle as the target object,
var offset:Object = getOffset(my_hero.mc, some_obstacle.mc);
After getting the resulting offset values, compare the magnitude (absolute value) of offset.x and offset.y. The outcome can be summarized as follows:
Let absDx be Math.abs(offset.x), absDy be Math.abs(offset.y),
absDx < absDy
offset.y < 0, target is above source
offset.y > 0, target is below source
absDx > absDy
offset.x < 0, target is to the left of source
offset.x > 0, target is to the right of source
absDx == absDy
refer to one of the above cases, doesn't really matter
Then you can update the position of your hero character according to different situations.
For your second question concerning implementing a very simple AI algorithm for your creatures, you can make use of the strategy above for your creatures to verify if they collide with any other stuff or not. If they do collide, assign them other directions of movement, or even simpler, just flip the signs(+/-) of their velocities and they will travel in opposite directions.
It is easier to implement simple algorithms first. Once it is working, you can apply whatever enhancements you like afterwards. For example, change directions when reaching junctions or per 3 seconds etc.

movie clip within parent flash move stops entire movie

I'm a bit new to Flash. As I was developing my movie, I introduced 3 layers of sequential animation that I decided I wanted to loop X times. So I copied the frames, created a new Movie Clip symbol, pasted the frames into it, then deleted the original on the stage and dragged this new clip as an instance (my_animation) in its place. All good so far.
However, when I play the entire movie, my_animation looped indefinitely, so I added a stop() action into that movie clip. That worked - plays once. I then added the following as an action on the very last keyframe of the main scene to try and get my_animation to loop X times:
var i = 1;
for (i = 1;i < 5;i++)
{
my_animation.play();
}
stop();
However, my_animation still only plays once. It does not appear to loop as I expect. I also tried replacing my_anmiation.play() with gotoAndPlay(117) where 117 is the frame containing the movie clip, but still the same.
Any help appreciated.
Thanks
UPDATE: I added a trace(i); statement within the loop. In the Output tab, I see:
1
2
3
4
…etc. SO - my_animation is not firing within the loop.
if you call my_animation.play(); with in "for loop" like that, it just calls 5 time consecutively and it just starts animation .
if you call my_animation.play(); during animation of my_animation nothing
happens. it works if it has stopped...
. so you need to listen add callback for to understand that animation finished and you can start that animation again..
var animatedCount:int = 0;
my_animation.addFrameScript(my_animation.totalFrames-1, onMyAnimationEnds);
my_Animation.play();
function onMyAnimationEnds():void{
animatedCount++;
if(animatedCount < 5)
{
my_Animation.play();
}
}
this will animate my_animation for 5 time...