AS3 Bouncing Ball - actionscript-3

Okay, after learning tutorials online, I'm trying to make a bouncing ball in AS3.
Here's my code thus far:
var count:Number = 0;
var bounceHeight:Number = 100;
var floorHeight:Number = 300;
var speed:Number = .1;
function run(e:Event):void
{
ball_mc.y = floorHeight - Math.abs(Math.cos(count)) * bounceHeight;
count += speed;
}
{
this.addEventListener(Event.ENTER_FRAME(run));
}
Thanks in advance for the help!
EDIT: The compiler errors are
Scene 1, Layer 'Layer 1', Frame 1, Line 13 1195: Attempted access of
inaccessible method ENTER_FRAME through a reference with static type
Class.
Scene 1, Layer 'Layer 1', Frame 1, Line 13 1136: Incorrect
number of arguments. Expected 2.

Within your closure, addEventListener requires a type parameter and a listener function.
Your type is Event.ENTER_FRAME and your handler is run, which means to call run every frame you need:
addEventListener(Event.ENTER_FRAME, run);
Therefore, your code should be:
function run(e:Event):void
{
ball_mc.y = floorHeight - Math.abs(Math.cos(count)) * bounceHeight;
count += speed;
}
this.addEventListener(Event.ENTER_FRAME, run);

Related

AS3: Call to a possibly undefined method addEventListener through a reference with static type Class

I am getting the following errors:
Scene 1, Layer 'Actions', Frame 1, Line 110, Column 14 1061: Call to a possibly undefined method addEventListener through a reference with static type Class.
Scene 1, Layer 'Actions', Frame 1, Line 113, Column 14 1061: Call to a possibly undefined method removeEventListener through a reference with static type Class.
Scene 1, Layer 'Actions', Frame 1, Line 128, Column 14 1061: Call to a possibly undefined method addEventListener through a reference with static type Class.
Scene 1,
Layer 'Actions', Frame 1, Line 131, Column 14 1061: Call to a possibly
undefined method removeEventListener through a reference with static
type Class.
the code part is:
function allowTapCaveman():void {
/*line 110*/ btn_caveman.addEventListener(TouchEvent.TOUCH_TAP, btn_cavemanMenu);
}
function cancelTapCaveman():void {
/*line 113*/ btn_caveman.removeEventListener(TouchEvent.TOUCH_TAP, btn_cavemanMenu);
}
function allowTapCavemanClose():void {
/*line 128*/ btn_caveman.addEventListener(TouchEvent.TOUCH_TAP, btn_cavemanMenuClose);
}
function cancelTapCavemanClose():void {
/*line 138*/ btn_caveman.removeEventListener(TouchEvent.TOUCH_TAP, btn_cavemanMenuClose);
}
btn_caveman is a movieclip (yeah I know I have 'btn') that gets called on the stage via an array;
var startingcaveman:Array = new Array();
for (var i:Number = 0; i<2; i++) {
startingcaveman.push(new btn_caveman());
addChild(startingcaveman[i]);
startingcaveman[i].name = 'startingcavemen' +i;
startingcaveman[i].x = Math.random()*550;
startingcaveman[i].y = Math.random()*400;
}
startingcaveman[0].x = 213.60;
startingcaveman[0].y = 312.90;
startingcaveman[1].x = 211.75;
startingcaveman[1].y = 400.15;
stage.addEventListener(Event.ENTER_FRAME, example);
function example (evt:Event) {
for each (var btn_caveman in startingcaveman) {
addEventListener(TouchEvent.TOUCH_TAP, btn_cavemanMenu3);
}
}
It's probably so simple but I can't get it which is annoying the hell outta me.
The simple answer which should allow you to fix your problem and in view of your coding style maybe get rid of many future problems as well:
You cannot use as a variable name the name of a class. In your case you have a class named btn_caveman but later on you try to use a variable named btn_caveman as well. Do not do that ever.
If you were to follow coding conventions you would never run into those type of problems. Class names should be that way:
ButtonCaveman
Variable name should be that way:
buttonCaveman
This should to it
var startingcaveman:Array = [];
for (var i:Number = 0; i<2; i++) {
// symbols should start with an upcase letter,
// because they're classes
// stick to "Caveman" for example
var btn:MovieClip = new btn_caveman();
startingcaveman.push(btn);
addChild(btn);
btn.name = 'startingcavemen' +i;
btn.x = Math.random()*550;
btn.y = Math.random()*400;
}
startingcaveman[0].x = 213.60;
startingcaveman[0].y = 312.90;
startingcaveman[1].x = 211.75;
startingcaveman[1].y = 400.15;
stage.addEventListener(Event.ENTER_FRAME, example);
function example (evt:Event) {
// here was the error. you used the class name.
// that's why naming is important!
for each (var btn in startingcaveman) {
btn.addEventListener(TouchEvent.TOUCH_TAP, btn_cavemanMenu3);
}
}

EventListener AS3 problems reset problems

Hey guys I am having a problem with Event Listeners in my AS3 file. I am trying to make this object that lasts for 83 frames to appear in a different location every time the parent (83 frame) movie clip resets. The problem is I have a function that places the object at a random y value which works great once. When it resets the ojbect appears on the same Y point. This is because I removeEventListener the function otherwise the object goes shooting off the screen when it loads. How do I call that event listener again without causing a loop that will shoot the object off screen?
Here is my code:
import flash.events.Event;
stop();
addEventListener(Event.ENTER_FRAME, SeaWeedPostion);
//stage.addEventListener(Event.ADDED_TO_STAGE, SeaWeedPostion);
function SeaWeedPostion(e:Event):void{
// if(newSeaWeed == 1) {
var randUint:uint = uint(Math.random() *500 + 50);
this.seaweedSet.y += randUint;
trace(randUint);
stopPos();
//}else{
//nothing
// }
}
function stopPos():void{
removeEventListener(Event.ENTER_FRAME, SeaWeedPostion);
//var newSeaWeed = 0;
}
function resetSeaWeed():void{
addEventListener(Event.ENTER_FRAME, SeaWeedPostion);
}
I have some // code in there from trying different things.
Anyone have any suggestions?
Thanks!
ENTER_FRAME event is triggered every frame, so rather than changing position on each frame maybe it's better to create a counter, count frames and if it reaches 82 change position of SeaWeed.
var counter:uint = 0;
Now add ENTER_FRAME listener
addEventListener(Event.ENTER_FRAME, onEnterFrame);
function SeaWeedPostion(e:Event):void {
counter++;
//Are we there yet?
if(counter < 83) {
//Nope, carry on
}
else {
//Yey!
changePosition();
counter = 0;
}
}
//Reset SeaWeed position when called
function changePosition() {
var randUint:uint = uint(Math.random() *500 + 50);
this.seaweedSet.y += randUint;
trace(randUint);
}

how to remove a child object by removeChild()?

I'm trying to make a custom animated/shooter, from this tutorial: http://flashadvanced.com/creating-small-shooting-game-as3/
By custom, I mean customized, ie, my own version of it.
In it's actionscript, there's a timer event listener with function: timerHandler()
This function adds and removes child "star" objects on the stage (which the user has to shoot at):
if(starAdded){
removeChild(star);
}
and :
addChild(star);
Code works great, but error occurs on scene 2.
The code works great, and I even added some code while learning via google and stackflow to this flash file. I added Scene 2 to it too, and had it called after 9 seconds of movie time. But when it goes to Scene 2, it still displays the star objects and I've been unable to remove these "star" object(s) from Scene 2.
Here's the code I added:
SCENE 1:
var my_timer = new Timer(5000,0); //in milliseconds
my_timer.addEventListener(TimerEvent.TIMER, catchTimer);
my_timer.start();
var myInt:int = getTimer() * 0.001;
var startTime:int = getTimer();
var currentTime:int = getTimer();
var timeRunning:int = (currentTime - startTime) * 0.001; // this is how many seconds the game has been running.
demo_txt.text = timeRunning.toString();
function catchTimer(e:TimerEvent)
{
gotoAndPlay(1, "Scene 2");
}
SCENE 2:
addEventListener(Event.ENTER_FRAME,myFunction);
function myFunction(event:Event) {
timer.stop();
timer.removeEventListener(TimerEvent.TIMER, timerHandler);
stage.removeChild(star);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, cursorMoveHandler);
my_timer.stop(); // you might need to cast this into Timer object
my_timer.removeEventListener(TimerEvent.TIMER, catchTimer);
Mouse.show();
}
stop();
=====================================================
I'm quite new as3, and have just created an account on StackOverflow... even though I've known and read many codes on it since quite some time.
Here's the Edited New Complete Code:
//importing tween classes
import fl.transitions.easing.*;
import fl.transitions.Tween;
//hiding the cursor
Mouse.hide();
//creating a new Star instance
var star:Star = new Star();
var game:Game = new Game();
//creating the timer
var timer:Timer = new Timer(1000);
//we create variables for random X and Y positions
var randomX:Number;
var randomY:Number;
var t:int = 0;
//variable for the alpha tween effect
var tween:Tween;
//we check if a star instance is already added to the stage
var starAdded:Boolean = false;
//we count the points
var points:int = 0;
//adding event handler on mouse move
stage.addEventListener(MouseEvent.MOUSE_MOVE, cursorMoveHandler);
//adding event handler to the timer
timer.addEventListener(TimerEvent.TIMER, timerHandler);
//starting the timer
timer.start();
addChild(game);
function cursorMoveHandler(e:Event):void{
//sight position matches the mouse position
game.Sight.x = mouseX;
game.Sight.y = mouseY;
}
function timerHandler(e:TimerEvent):void{
//first we need to remove the star from the stage if already added
if(starAdded){
removeChild(star);
}
//positioning the star on a random position
randomX = Math.random()*500;
randomY = Math.random()*300;
star.x = randomX;
star.y = randomY;
//adding the star to the stage
addChild(star);
//changing our boolean value to true
starAdded = true;
//adding a mouse click handler to the star
star.addEventListener(MouseEvent.CLICK, clickHandler);
//animating the star's appearance
tween = new Tween(star, "alpha", Strong.easeOut, 0, 1, 3, true);
t++;
if(t>=5) {
gotoAndPlay(5);
}
}
function clickHandler(e:Event):void{
//when we click/shoot a star we increment the points
points ++;
//showing the result in the text field
points_txt.text = points.toString();
}
And on Frame 5 :
//timer.stop();
//timer.removeEventListener(TimerEvent.TIMER, timerHandler);
// uncomment lines above if "timer" is something you've made
stage.removeChild(star);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, cursorMoveHandler);
timer.stop(); // you might need to cast this into Timer object
timer.removeEventListener(TimerEvent.TIMER, timerHandler);
Mouse.show();
stop();
There's no Scene 2 now, in this new .fla file...
Here's a screenshot of the library property of my flash file...: http://i.imgur.com/d2cPyOx.jpg
You'd better drop scenes altogether, they are pretty much deprecated in AS3. Instead, use Game object that contains all the cursor, stars and other stuff that's inside the game, and instead of going with gotoAndPlay() do removeChild(game); addChild(scoreboard); where "scoreboard" is another container class that will display your score.
Regarding your code, you stop having a valid handle to stage that actually contains that star of yours, because your have changed the scene. So do all of this before calling gotoAndPlay() in your catchTimer function.
function catchTimer(e:TimerEvent)
{
//timer.stop();
//timer.removeEventListener(TimerEvent.TIMER, timerHandler);
// uncomment lines above if "timer" is something you've made
stage.removeChild(star);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, cursorMoveHandler);
my_timer.stop(); // you might need to cast this into Timer object
my_timer.removeEventListener(TimerEvent.TIMER, catchTimer);
Mouse.show();
gotoAndPlay(1, "Scene 2");
}
And the code for Scene 2 will consist of a single stop() - until you'll add something there. Also, there should be no event listeners, especially enter-frame, without a code to remove that listener! You add an enter-frame listener on Scene 2 and never remove it, while you need that code to only run once.
Use getChildAt.
function catchTimer(e:TimerEvent)
{
var childCount:int = this.numChildren - 1;
var i:int;
var tempObj:DisplayObject;
for (i = 0; i < childCount; i++)
{
tempObj = this.getChildAt(i);
this.removeChild(tempObj);
}
gotoAndPlay(1, "Scene 2");
}
This will remove all the children you added on scene 1 before going to scene 2.

Creating Multiple Levels AS3

Hey Guys so I'm having a little trouble creating Multiple levels. I'm not so sure if im creating them the right way but i have a player and goal_1, goal_2, etc.. Basically when the player hitTestObject the goal_1 i want it to go to a new function called level_2 then level_3 after that hitTest. so Level_1 works just fine the hitTest works and it initializes level_2 but when i try to hitTest the player and goal_2 or even goal_1 again it just goes through it and doesnt do anything.
I understand now that level_2 isnt being called every frame like level_1 since its not part of the Enter_Frame listener. But i cant figure out how to have multiple Enter Frame events and not have them run simultaneously. If thats even the right way to create multiple levels.
Can you see what i could do in order to make it work?
private function gameLoop(e:Event):void
{
playerShoot();
playerControl();
playerStageBoundaries();
checkEndGameCondition();
checkPlayerOffScreen();
level_1();
}
private function level_1():void
{
if(player.hitTestObject(mGoal_1))
{
trace("Goal_1 Collision");
//Remove button for constant movement
btnShootPlayer = false;
mGoal_1.destroyGoal_1();
player.destroyPlayer();
//Update High Score text
nScore += 10;
updateHighScore();
stage.removeEventListener(Event.ENTER_FRAME, gameLoop);
//Update level
nLevel++;
updatePlayerLevel();
level_2();
}else
{
checkEndGameCondition();
}
}
public function level_2():void
{
stage.addEventListener(Event.ENTER_FRAME, gameLoop);
TweenMax.to(mGoal_1, 1, {y:40, repeat:-1, yoyo:true, ease:Power0.easeInOut});
trace("Level_2 Initiated");
//Keep Text Scores initiated
updateHighScore();
updatePlayerLives();
player = new mPlayer();
stage.addChild(player);
player.x = (stage.stageWidth / 2) - 280;
player.y = (stage.stageHeight / 2);
mGoal_1 = new goal_1();
stage.addChild(mGoal_1);
mGoal_1.x = (stage.stageWidth / 2) + 300;
mGoal_1.y = (stage.stageHeight) - 35;
if (player.hitTestObject(mGoal_1))
{
trace("Level 2 Hit test works!");
nScore += 10;
updateHighScore();
}
}
I didn't read too carefully all the code, but I guess you can use a function variable. Declare it on class level (outside any function):
var _doFunction:Function;
than, instead calling level1 function, pass the reference and call the _doFunction:
_doFunction = level1;
_doFunction();//or _doFunction.call(); - see Adobes documentation
when you are done with the level1, than pass the next level:
_doFunction = level2;
P.S. don't forget to accept the answer if it helped to solve your problem.

converting Actionscript 2 code into Actionscript 3

Recently I followed and made the 3d carousel in AS2, but I'm looking to use it and make it in AS3. Is there any possible way of converting the code so the carousel can work in AS3?
Below is the code for the AS2 carousel:
import mx.utils.Delegate;
var numOfItems:Number;
var radiusX:Number = 300;
var radiusY:Number = 75;
var centerX:Number = Stage.width / 2;
var centerY:Number = Stage.height / 2;
var speed:Number = 0.05;
var perspective:Number = 130;
var home:MovieClip = this;
var tooltip:MovieClip = this.attachMovie("tooltip","tooltip",10000);
tooltip._alpha = 0;
var xml:XML = new XML();
xml.ignoreWhite = true;
xml.onLoad = function()
{
var nodes = this.firstChild.childNodes;
numOfItems = nodes.length;
for(var i=0;i<numOfItems;i++)
{
var t = home.attachMovie("item","item"+i,i+1);
t.angle = i * ((Math.PI*2)/numOfItems);
t.onEnterFrame = mover;
t.toolText = nodes[i].attributes.tooltip;
t.icon.inner.loadMovie(nodes[i].attributes.image);
t.r.inner.loadMovie(nodes[i].attributes.image);
t.icon.onRollOver = over;
t.icon.onRollOut = out;
t.icon.onRelease = released;
}
}
function over()
{
home.tooltip.tipText.text = this._parent.toolText;
home.tooltip._x = this._parent._x;
home.tooltip._y = this._parent._y - this._parent._height/2;
home.tooltip.onEnterFrame = Delegate.create(this,moveTip);
home.tooltip._alpha = 100;
}
function out()
{
delete home.tooltip.onEnterFrame;
home.tooltip._alpha = 0;
}
function released()
{
trace(this._parent.toolText);
}
function moveTip()
{
home.tooltip._x = this._parent._x;
home.tooltip._y = this._parent._y - this._parent._height/2;
}
xml.load("icons.xml");
function mover()
{
this._x = Math.cos(this.angle) * radiusX + centerX;
this._y = Math.sin(this.angle) * radiusY + centerY;
var s = (this._y - perspective) /(centerY+radiusY-perspective);
this._xscale = this._yscale = s*100;
this.angle += this._parent.speed;
this.swapDepths(Math.round(this._xscale) + 100);
}
this.onMouseMove = function()
{
speed = (this._xmouse-centerX)/2500;
}
When I add this code in AS3 I get the following error:
Scene 1, Layer 'Layer 1', Frame 1, Line 1 1172: Definition mx.utils:Delegate could not be found.
Scene 1, Layer 'Layer 1', Frame 1, Line 1 1172: Definition mx.utils:Delegate could not be found.
Scene 1, Layer 'Layer 1', Frame 1, Line 41 1120: Access of undefined property Delegate.
Scene 1, Layer 'Layer 1', Frame 1, Line 6 1119: Access of possibly undefined property width through a reference with static type Class.
Scene 1, Layer 'Layer 1', Frame 1, Line 7 1119: Access of possibly undefined property height through a reference with static type Class.
I'm quite new to AS2 and AS3 but after some research I understand that import mx.utils.Delegate; is no longer need in AS3 as it already has delegate and they are already built in so in the code so I delete the delegate which are line 1 and line 41 and got two errors:
Scene 1, Layer 'Layer 1', Frame 1, Line 6 1119: Access of possibly undefined property width through a reference with static type Class.
Scene 1, Layer 'Layer 1', Frame 1, Line 7 1119: Access of possibly undefined property height through a reference with static type Class.
Now I cant figure out what to do so can someone help me convert this code from AS2 to AS3?
You have quite a few things to address here:
Your mouse events need to be changed to as3 calls
t.icon.onRollOver = over, in as3 looks more like t.icon.addEventListener(MouseEvent.ROLL_OVER, over);
attachMovie is no longer used in as3.
you need to export for actionscript the movie you want to get from the library with a unique class name, then use new someName(); to create it. Then it must be added to the display list with addChild
onEnterFrame is not used in as3, you need to create an enterframe event more like this: **addEventListener(Event.ENTER_FRAME, someFunction);
delegate is not used in as3.
flags on _x, _y, _parent, _alpha etc have been removed in as3. just use x,y, parent, alpha etc.
swapDepths has been removed from as3, You need to use the display list to add/remove/swap levels.
sounds like you might need to study up a little on as3 before you can properly tackle this one! try checking out this link for comparisons between as2 and as3 functionality.
http://www.actionscriptcheatsheet.com/downloads/as3cs_migration.pdf