Animating from within classes in Actionscript 3 (Not on the timeline), what's the best way? - actionscript-3

I've found some stuff online about how to animate in actionscript 3 from within a class, but haven't been able to find a really good tutorial. I want to control the animations from a class because at some point I intend to move from the flash IDE to using flash develop, where I won't have access to the Flash IDE's timeline.
I have to be able to control an initial animation (opening a bag) which joins onto an animation loop (searching through a bag).
The only way I have been able to do this so far is to add an event listener to listen for the initial animation's final frame. Then when initialAnimation.currentFrameLabel = "Last" then I gotoAndStop("animationLoop").
This has been working fine, if a bit time-consuming. I'm just wondering if there's a better, easier way to do it? Can anyone tell me or point me towards a tutorial that does it better? Thanks very much!
Romano

I recommend instead of using an event listener, you use the method addFrameScript. Essentially you can fire a method when a specific frame number is reached.
Read the following question for more information.
actionscript3 whats the point of addFrameScript

It depends on what it is you want to do:
Usually if you are working together with an artist or want to do animations that are non-code driven, the "best way" is usually to listen for something to happen, and then start animations and on last frame of animation (or when you want to return control to code) you create an event, or use a callback or something else to let code notify that animation is complete or reached a certain point.
If you want to do something from code, the easiest way is to use an external animation library.
Tweener (https://code.google.com/p/tweener/)
TweenLite (http://www.greensock.com/tweenlite/)
Using those libraries, you would write something similar to:
function fadeOut():void {
mc.alpha = 1;
Tweener.addTween(mc, {alpha:0, time:0.275, delay:1, onComplete:onDone});
}
function onDone():void {
trace("Animation finished");
}

Related

Errors when switching scenes in flash AS3

In my little Flash project, I use the Enter Frame Gameloop commands, and I use hittestobject and such then put that function in to the game loop. However, When switching scenes I am bombarded with errors because the objects included in the functions are not on screen anymore. My question is how can I either take those functions out of the game loop when changing from that specific scene, or write the code so it only includes that one specific scene. Like: if current frame = 2, or something in real code form. Thankyou so much I am very appreciative for any replies.
function gameLoop(evnt:Event){
try{
//Write your all codes
}catch(err:Error){
}
}
Use try/ catch.
I don't know the way you change scenes.
Based on your description,I guess the way you change scenes is to go to different frames.Am I right?
If I am right,I think you can declare a variable to mark if you need to do the hittestobject function or other operations.
such as:
gameloop(){
if(!changing)
a.hitTestObject(b)
}

Best Way To Implement Invincibility Frames in AS3

I'm making a little flash game and I want to implement invincibility frames, but I'm not exactly sure how to go about doing it. Essentially, when the player walks over an object, I want to remove a health (I know how to do this) and then have invincibility frames so that the player has time to move off of the object. Something along the lines of
if (player.hitTestObject(spikes)) {
//remove health
// INVINCIBILITY FRAMES
}
Any direction here would be helpful. Thanks!
You'd better give some details about your programming style, I mean is your programming style pure as3 or pure stage or using both as3 and stage.
I'm gonna answer your question assuming you're using pure as3 style.
If you want to make your hero invincible for everything instead of just that hitted spike, you should add a public method in your hero's ( or character's) class and a variable to keep track of how much time left to remove invincibility. Something like this
public function gotHit(){
invincibilityTimeLeft=500;//500 is miliseconds, which is a half second edit this as you wish.
isInvincible=true;
}
then in your game's Event.ENTER_FRAME loop, you should decrease your character's invincibilityTimeLeft according to passed time. When it reaches 0 or below again, you set isInvincible variable of your character as false. I hope you understand what I mean.
Best of lucks.
-Ozan

How do I create a simple on-mouse-click rotating object in flash

This question may get downvoted or go unanswered because it's not the greatest and incredible silly but anyway,
I'm taking an intro level Webanimation course this semester at UNI and had I know what their expectations are for our hand-in projects i would have never taken it up.
Basically the teacher taught us stuff to the extent of masking/tweening and very few mouse-event and basic function codes.
Now she is expecting us to make a god damn ENTIRE PIPE GAME. The one where there are a bunch of rotating pipes and you gotta rotate them in place before a timer runs out and then the water flows through them.
For this project I have to somehow figure out the following (even though she didn't teach any of this):
-creature a grid of rotate-able pipes (one mouse click I assume would do a 90 degree classic tween rotation of the object)
-creature some sort of logic hit-box value chain to make pipes decide when to fill with water (they fill with water (a.k.a turn blue inside as an animation) once they are connected to another water filled pipe, for example)
-creature multiple levels and a menu screen
-add a music track.
Now i know this site is for specific help only and you basically can't ask for help on an entire project, so for now if somebody could just help me out with the following:
How do I create a rotating pipe on mouseclick?
So I have my pipe movieclip created and I have my Mouse Event code ready but I don't have the faintest on how to make a tween within the pipe and connect it to the code so that it rotates on mouseclick.
So this far, let's say for one of the pipes, instance pipe_1, I want to do this:
pipe_1.addEventListener(MouseEvent.CLICK, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
trace("Mouse clicked");
}
I also have the simple tween of rotation already created within the instance of the pipe, but dunno how to connect it to code.
I'm supposed to figure out what to put inside the function but I honestly have no clue. Hours of googling have come up with nothing either except a 12 dollar purchasable source code for an even more complicated pipe game.
I hope somebody can at least help a bit, and thanks.
The way to rotate a clip is via it's rotation property. It defaults to 0.
If you were set the rotation property of your tile to 90, you'd rotate your pipe tile 90 degrees.
for example :
pipe_1.rotation += 90;
A tween is a means of changing a property of a given DisplayObject over time. So what you want to do is tween your rotation property 90 degrees over time.
Here is a tutorial on Tweening - http://www.republicofcode.com/tutorials/flash/as3tweenclass/
I think it'd be more beneficial for you to take the time to learn about it, than to have me just write a few lines of code to solve your problem.
StackOverflow is a place where you can ask a question, AFTER you have tried something and have hit an issue.
I have provided you with the basic concept of what you need to do, and if you take the time to learn about tweening, you'll be able to achieve your goal rather simply.
There are also tweening libraries such as TweenLite and TweenMax that simplify tweening. Not sure if your class will allow you to use them, but worthwhile to check out for your own benefit.
You can find TweenLite here :
http://www.greensock.com/tweenlite/
Are you talking about a frame by frame tween? or tweening with code?
for frame by frame tweening, you can try to do this:
pipe_1.addEventListener(MouseEvent.CLICK, f1_MouseClickHandler);
function f1_MouseClickHandler(e:MouseEvent) {
pipe_1.gotoAndPlay(2); //if the tween starts at frame 2
}
For code tweening, just call the tween function inside that handler function

leaving and revisting a scene keeping any user input changes the same. Can it be done?

Hi Im relatively new to flash developing and i have a quick question about saving user input. I have a maze scene whereby the user navagates a character around until confronted with another object, when the character hits the object a new scene is opened promting the user to pick a solution to a problem. Once the user clicks the correct answer a box appears saying return to the maze, however when clicked and returned to the maze the character starts back in its original postion, where as I would like the scene to resume where it left off, ie the character is at the point where it collided with the object, the object has dissappeared and the character can resume on the same course.
Thanks for giving this a read I hope it makes sense and some one has a solution for me.
I did have some nice images to explain it better but apprently i need 10 reputation points to upload those.
EDIT: First Id like to say thanks for the rep points you bunch of stars and secondly I know using scenes in flash is seriously cr*p practice and outdated but its the way I learnt all those years ago and seen as Flash itself will be outdated soon Im not really looking to learn another approach using sprites or frames, I just kind of want a fix for this way if poss thank you for answering!
EDIT: Wanting the red rectangle to be removed from the scene once the black square collides with it. It also takes you to the next frame upon doing so. here is my code.
addEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);
function fl_EnterFrameHandler (event:Event):void
{
if (player.hitTestObject(Risk))
{
removeEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);
removeChild(Risk);
nextFrame();
}
}
I'd suggest you forget about Scenes! They are old, buggy, bring loads of issues with code and are generally a Bad Pratice!! So if you are just learning AS3, dont learn with Scenes!!
Use MovieClips or Sprites instead. And just add and remove them as you need!
EDIT:
To ur edit ;)
and seen as Flash itself will be outdated soon
thats just plain false and a widespread misinformation. It just has a new purpose like MultiPlattform Game Development. But thats a whole different discussion.
You could solve this by saving the x,y coordinates and then restoring them. But i promise you, you will run in to alot more problems/bugs as you go allong!
Like saved Points and Time. Will you triger the Questionscene again when u place the player on the object(last Position). Save the answers, and so on ...
Changing to DisplayObjects will save you time in the end. Just saying ;)
EDIT2:
your code in the comment should look like this:
function fl_EnterFrameHandler (event:Event):void
{
if (player.hitTestObject(Risk))
{
removeEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);//remove to prevent errors if it fires again and there is no Object to hitTest
removeChild(Risk);// do what needs to be done on this frame
nextFrame();// and then move to the next
}
}
And following correct convetions and make everybody's life easier reading this, it would look like this!
function fl_EnterFrameHandler (event:Event):void
{
if (player.hitTestObject(risk))
{
removeEventListener(Event.ENTER_FRAME, fl_EnterFrameHandler);//remove to prevent errors if it fires again and there is no Onject to hitTest
removeChild (risk);
nextFrame ();
}
}
i'm probaly confusing u now, just use the top one ;)
EDIT3:
Ok, i just had a butchers at it. It's all on a single Frame now. I would have prefered Classes but that'lljust confuse you.
To add new qestions you just have to dublicate the Question MovieClip in the Library and change texts, leave instance names the same tho, then the code will work as is!
DOWLOAD
It is certainly possible. You would store the characters attributes (e.g. current position) within a variable. Then on returning to your game you would use this variable to set the starting position of your character.
I agree that scenes are not the ideal route you should be taking. Possibly reading a good AS3 book would save you hours/days/weeks in the long run.

Actionscript to play/pause audio on different buttons

I've created a few buttons in Flash. I'm trying to make it so that if you click one button, the audio starts playing for that button. If you click another button, the active audio stops and the new audio of the button you clicked last start playing.
Any help please?
What you're describing is actually quite easy to do.
First things first, I recommend importing the audio into your Flash project. Alternatively, there is a way to play it directly from an external file. This is beyond the scope of my answer, so if you need help on that, you should post a question specifically covering it.
Assuming you have imported the audio file into your Flash project's library, make an as3 instance of it. (Right click the file in the library, click Properties --> ActionScript [tab] --> [Check] Export for ActionScript & [Enter name in] Class)
Now, create a definition of the sound in your code. (Assuming your two sounds were named "mySound1" and "mySound2" in the Class field of the previous step.)
var mySound1:Sound = new mySound1();
var mySound2:Sound = new mySound2();
Now, define your sound channel.
var mySoundChannel:SoundChannel = new SoundChannel();
There are two alternate ways of stopping one sound and playing another. The first is to create one function that does both every time. The second method is to create two formulas, one for "play" and one for "stop". You will need to decide which method works best for you. I'll use the two-function method below:
function stopSound():void
{
//This stops all sound in the sound channel.
//If there is nothing playing, nothing happens.
mySoundChannel.stop();
}
//In this function, we create an argument that allows us to tell the function
//what sound to we want it to play.
function playSound(soundname:String):void
{
mySoundChannel = this[soundname].play(0, 0);
}
[Note, you can tweak the play() properties to meet your needs, doing things like starting in the middle of the song, or looping it forever. 0,0 starts at the beginning, and doesn't loop. See the documentation for this.]
Now you hook up the event listeners for the buttons. (If you need help with event listeners, read the documentation.)
myButton1.addEventListener(Mouse.CLICK, btn1Click);
myButton2.addEventListener(Mouse.CLICK, btn2Click);
function btn1Click(evt:Event):void
{
stopSound();
playSound(mySound1);
}
function btn2Click(evt:Event):void
{
stopSound();
playSound(mySound2);
}
This should be enough information to get you started. In my game core, I actually have a custom class for dealing with sound playback that gives me the ability to repeat sounds, change volume, and keep sounds from conflicting with each other. I say that to emphasize that you can do quite a bit with the sound class. Do some digging in that documentation for ideas and help.
You may also consider putting a try-catch statement in the playSound function, since it will throw an reference error if you pass a name for a sound that doesn't exist.