Convert ActionScript 2.0 code to ActionScript 3.0 - actionscript-3

I currently follow a flash tutorial online to create an interactive sketchpad. The link to tutorial is http://flashexplained.com/actionscript/making-an-interactive-drawing-sketchpad/.
The only problem with this tutorial is that the code is for actionscript 2.0 instead of 3.0. I know how to redefine the variables but besides that I am clueless, so I was hoping that someone can help me convert the code to ActionScript 3.0.
Here is the ActionScript 2.0 code:
lineThickness = 0;
selectedColor = "0x000000";
_root.onMouseDown = startDrawing;
_root.onMouseUp = stopDrawing;
function startDrawing()
{
if(_xmouse < 455)
{
_root.lineStyle(lineThickness, selectedColor);
_root.moveTo(_root._xmouse, _root._ymouse);
_root.onMouseMove = drawLine;
}
}
function drawLine()
{
_root.lineTo(this._xmouse, this._ymouse);
}
function stopDrawing()
{
delete this.onMouseMove;
}
line0.onPress = function()
{
lineThickness = 0;
}
line3.onPress = function()
{
lineThickness = 3;
}
line6.onPress = function()
{
lineThickness = 6;
}
colorRed.onPress = function()
{
selectedColor = "0xFF0000";
}
colorGreen.onPress = function()
{
selectedColor = "0x00FF00";
}

AS2:
lineThickness = 0;
selectedColor = "0x000000";
AS3:
var lineThickness:int = 0;
var selectColor:uint = 0x000000;
AS2:
_root.onMouseDown = startDrawing;
_root.onMouseUp = stopDrawing;
function startDrawing()
{
if(_xmouse < 455)
{
_root.lineStyle(lineThickness, selectedColor);
_root.moveTo(_root._xmouse, _root._ymouse);
_root.onMouseMove = drawLine;
}
}
function stopDrawing()
{
delete this.onMouseMove;
}
function drawLine()
{
_root.lineTo(this._xmouse, this._ymouse);
}
AS3:
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
function startDrawing(e:MouseEvent):void
{
if(mouseX < 455)
{
this.graphics.lineStyle(lineThickness, selectedColor);
this.graphics.moveTo(mouseX, mouseY);
stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
}
}
function stopDrawing(e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
}
function mouseMove(e:MouseEvent):void
{
this.graphics.lineTo(mouseX, mouseY);
}
AS2:
line0.onPress = function()
{
lineThickness = 0;
}
line3.onPress = function()
{
lineThickness = 3;
}
line6.onPress = function()
{
lineThickness = 6;
}
colorRed.onPress = function()
{
selectedColor = "0xFF0000";
}
colorGreen.onPress = function()
{
selectedColor = "0x00FF00";
}
AS3:
line0.addEventListener(MouseEvent.CLICK, changeLine);
line3.addEventListener(MouseEvent.CLICK, changeLine);
line6.addEventListener(MouseEvent.CLICK, changeLine);
colorRed.addEventListener(MouseEvent.CLICK, changeColor);
colorGreen.addEventListener(MouseEvent.CLICK, changeColor);
function changeLine(e:MouseEvent):void
{
switch(e.currentTarget)
{
default: lineThickness = 1; break;
case line0: lineThickness = 0; break;
case line3: lineThickness = 0; break;
case line6: lineThickness = 0; break;
}
}
function changeColor(e:MouseEvent):void
{
switch(e.currentTarget)
{
default: selectedColor = 0x000000;
case colorRed: selectedColor = 0xFF0000; break;
case colorGreen: selectedColor = 0x00FF00; break;
}
}
Additional (clear the graphics):
eraser_btn.addEventListener(MouseEvent.CLICK, erase);
function erase(e:MouseEvent):void
{
this.graphics.clear();
}

I recommend you read this http://www.actionscriptcheatsheet.com/downloads/as3cs_migration.pdf
But, here is some tips.
Events you code like this
object.addEventListener(Event.EVENT_TYPE,myFunctionToHandleTheEvent);
in the case of
_root.lineStyle(lineThickness, selectedColor);
_root.moveTo(_root._xmouse, _root._ymouse);
you use this
this.graphics.lineStyle(lineThickness, selectedColor);
this.graphics.moveTo(stage.mouseX, stage.mouseY);
to remove a event listener use
object.removeEventListener(Event.EVENT_TYPE,myFunction);

Related

Shoot in different directions in as3

I'm having some troubles with the game I'm making. My character shoots bullets, but when it comes to shooting them in different directions it does not work properly. When it shoots the bullets follow the character's direction. Below I post the code.
var Bulli:Array = new Array();
var ShootTimer:Timer = new Timer(0);
stage.addEventListener(MouseEvent.MOUSE_DOWN, startShootTimer);
stage.addEventListener(MouseEvent.MOUSE_UP, stopShootTimer);
ShootTimer.addEventListener(TimerEvent.TIMER, shootBullo);
stage.addEventListener(Event.ENTER_FRAME, mainLoop);
function startShootTimer(e:MouseEvent):void
{
ShootTimer.start();
}
function stopShootTimer(e:MouseEvent):void
{
ShootTimer.stop();
}
function shootBullo(e:TimerEvent):void
{
var bullo:Bullo = new Bullo();
bullo.x = Jumbo.x;
bullo.y = Jumbo.y - 50;
if(destra)
{
bullo.dir = destra;
}
else
{
bullo.dir = sinistra;
}
addChild(bullo);
Bulli.push(bullo);
}
function mainLoop (e:Event):void
{
for (var b:int = 0; b < Bulli.length; b++)
{
if (Bulli[b].dir == destra)
{
Bulli[b].x += 10;
}
else
{
Bulli[b].x -= 10;
}
}
}
Don't add that listener to Stage, instead add it to each unique bullo...
//# not to Stage...
//stage.addEventListener(Event.ENTER_FRAME, mainLoop);
Try this (untested but may be useful for some ideas):
function shootBullo(e:TimerEvent):void
{
var bullo:Bullo = new Bullo();
bullo.x = Jumbo.x;
bullo.y = Jumbo.y - 50;
if(destra) { bullo.dir = destra; }
else { bullo.dir = sinistra; }
bullo.addEventListener(Event.ENTER_FRAME, mainLoop);
}
function mainLoop (e:Event):void //the "e" of this function parameter is each unique "Bullo"
{
//# currentTarget is whichever "bullo" is talking to this Event (via Listener).
if (e.currentTarget.dir == destra)
{ e.currentTarget.x += 10; }
else { e.currentTarget.x -= 10; }
}

Error #1009 sometimes during game

I have made a game on Flash CS6 using AS3. The game has a spaceship on the right hand of the screen and it shoots bullets at aliens that randomly appear on the right. The game is all working perfectly but every now and then when I play it i get this error.
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at alien3/pulse()[/Users/Matt/Documents/DES B Assignment/Prototype/alien3.as:43]
Now here is the AS linkage for alien 3
package {
import flash.display.MovieClip;
import flash.events.Event;
public class alien3 extends MovieClip {
var yMove:Number = 15;
var changeDirectionAfterYMoves:Number = 0;
var moveCount:Number = 0;
var shootCount:Number = 0;
var shootMissilesAfterYMoves:Number = 0;
public function alien3() {
addEventListener(Event.ENTER_FRAME,pulse);
}
public function stopListening()
{
removeEventListener(Event.ENTER_FRAME,pulse);
}
public function pulse(evt:Event)
{
if (currentFrame!=1) return;
if(changeDirectionAfterYMoves == moveCount)
{
yMove=yMove*-1;
var maxMoves:Number;
if (yMove>0)maxMoves = Math.round (400-this.y)/yMove;
else maxMoves = Math.round((this.y)/Math.abs(yMove));
changeDirectionAfterYMoves = 1 + Math.round (Math.random () *maxMoves);
moveCount = 0;
}
if (shootCount==shootMissilesAfterYMoves)
{
var ao:alienMissile3 = new alienMissile3 ();
ao.x = this.x + 50;
ao.y = this.y;
parent.addChild(ao);
shootCount=0;
shootMissilesAfterYMoves = 1 + Math.round (Math.random() * 25)
}
this.y+=yMove;
moveCount = moveCount+1;
shootCount = shootCount+1;
}
}
}
So line 43 responds to the alien missile movie clip in the library
parent.addChild(ao);
Which is strange because it adds the alien missiles without a problem and they work fine
The alienMissile3 is a movie clip which was converted to a movie clip from a png which is named something different.
I have no idea what is causing this error.
The code in the main timeline is as follows.
import flash.display.MovieClip;
import flash.events.Event;
import flash.media.SoundChannel;
import flash.net.dns.AAAARecord;
var frameCount:Number = 0;
var alienCount:Number = 0;
var alienInterval:Number = 100;
var score:Number=0;
var gameOn:Boolean = false
var my_sound:laserGun = new laserGun();
var my_channel:SoundChannel = new SoundChannel();
var my_sound3:QueenAmidalaandTheNabooPalace = new QueenAmidalaandTheNabooPalace();
var my_channel3:SoundChannel = new SoundChannel();
var spaceshipMovement:Number = 0;
mcGameOverScreen.visible=false;
var scoresArray:Array = new Array();
var SO:SharedObject = SharedObject.getLocal("scores5");
if (SO.size!=0)
{
scoresArray = SO.data.scoresArray;
}
function startGame()
{
addEventListener(Event.ENTER_FRAME, pulse);
gameOn=true;
mySpaceship.livesLeft=3;
score=0;
}
function pulse(event:Event):void
{
if (mySpaceship.livesLeft<1) noLivesLeft();
addNewAlienIfNecessary();
/*addNewAlien2IfNecessary();
addNewAlien3IfNecessary();*/
checkForMissileOnAlien();
checkForMissileOnAlien2();
checkForMissileOnAlien3();
checkForMissileOnAlienMissile();
checkForMissileOnAlienMissile2();
checkForMissileOnAlienMissile3();
tidyUp();
checkForAlienMissileOnSpaceship();
checkForAlienMissile2OnSpaceship();
checkForAlienMissile3OnSpaceship();
tbScore.text = String(score);
tbLivesLeft.text = String (mySpaceship.livesLeft);
var bg:background = new background();
bg.y = 0;
bg.x = 0;
addChild(bg);
gameOn=true;
}
function addNewAlienIfNecessary()
{
if (score<=100 && alienCount<3 && frameCount%60==0)
{
var a:alien = new alien();
a.x = Math.random()*380;
a.y = Math.random()*50;
addChild(a);
alienCount=alienCount+1;
}
//frameCount++;
if (score >100 && score<500 && alienCount<3 && frameCount%80==0)
{
var aa:alien2 = new alien2();
aa.x = Math.random()*380;
aa.y = Math.random()*50;
addChild(aa);
alienCount=alienCount+1;
}
//frameCount++;
if (alienCount<3 && score>=500 && frameCount%100==0)
{
var ab:alien3 = new alien3();
ab.x = Math.random()*380;
ab.y = Math.random()*50;
addChild(ab);
alienCount=alienCount+1;
}
frameCount++;
}
/*function addNewAlien2IfNecessary()
{
if (score>100 && score<500 && alienCount<3 && frameCount%60==0)
{
var aa:alien2 = new alien2();
aa.x = Math.random()*440;
aa.y = Math.random()*50;
addChild(aa);
alienCount=alienCount+1;
}
frameCount++;
}
function addNewAlien3IfNecessary()
{
if (score>500 && alienCount<3 && frameCount%60==0)
{
var ab:alien3 = new alien3();
ab.x = Math.random()*440;
ab.y = Math.random()*50;
addChild(ab);
alienCount=alienCount+1;
}
frameCount++;
}*/
function checkForMissileOnAlien()
{
var missilez:Array = new Array;
var alienz:Array = new Array;
for (var i=0;i<numChildren;i++)
{
if (getChildAt(i) is alien) {alienz.push(getChildAt(i) as MovieClip)};
if (getChildAt(i) is missile) {missilez.push(getChildAt(i) as MovieClip)};
}
for (var j=0;j<alienz.length;j++)
{
for (var k=0;k<missilez.length;k++)
{
if (alienz[j].hitTestObject(missilez[k]))
{
alienz[j].gotoAndStop (2);
//alienz[j].stopListening();
missilez[k].gotoAndStop(2);
missilez[k].stopListening();
var e:explosion = new explosion();
e.x = alienz[j].x;
e.y = alienz[j].y;
addChild(e);
alienCount = alienCount-1;
score += 20;
}
}
}
}
function checkForMissileOnAlien2()
{
var missilez:Array = new Array;
var alienz2:Array = new Array;
for (var i=0;i<numChildren;i++)
{
if (getChildAt(i) is alien2) {alienz2.push(getChildAt(i) as MovieClip)};
if (getChildAt(i) is missile) {missilez.push(getChildAt(i) as MovieClip)};
}
for (var j=0;j<alienz2.length;j++)
{
for (var k=0;k<missilez.length;k++)
{
if (alienz2[j].hitTestObject(missilez[k]))
{
alienz2[j].gotoAndStop (2);
//alienz2[j].stopListening();
missilez[k].gotoAndStop(2);
missilez[k].stopListening();
var e:explosion = new explosion();
e.x = alienz2[j].x;
e.y = alienz2[j].y;
addChild(e);
alienCount = alienCount-1;
score += 50;
}
}
}
}
function checkForMissileOnAlien3()
{
var missilez:Array = new Array;
var alienz3:Array = new Array;
for (var i=0;i<numChildren;i++)
{
if (getChildAt(i) is alien3) {alienz3.push(getChildAt(i) as MovieClip)};
if (getChildAt(i) is missile) {missilez.push(getChildAt(i) as MovieClip)};
}
for (var j=0;j<alienz3.length;j++)
{
for (var k=0;k<missilez.length;k++)
{
if (alienz3[j].hitTestObject(missilez[k]))
{
alienz3[j].gotoAndStop (2);
//alienz3[j].stopListening();
missilez[k].gotoAndStop(2);
missilez[k].stopListening();
var e:explosion = new explosion();
e.x = alienz3[j].x;
e.y = alienz3[j].y;
addChild(e);
alienCount = alienCount-1;
score += 100;
}
}
}
}
function checkForMissileOnAlienMissile()
{
var alienMissilez:Array = new Array();
var missilez:Array = new Array();
for (var i=0;i<numChildren;i++)
{
if (getChildAt(i) is alienMissile) {alienMissilez.push(getChildAt(i) as MovieClip);}
if (getChildAt(i) is missile) {missilez.push(getChildAt(i) as MovieClip);}
}
trace("alienMissilez" + alienMissilez.length);
trace("missilez" + missilez.length);
for (var j=0;j<alienMissilez.length;j++)
{
for (var k=0;k<missilez.length;k++)
{
if (alienMissilez[j].hitTestObject(missilez[k]))
{
alienMissilez[j].gotoAndPlay(2);
alienMissilez[j].stopListening();
missilez[k].gotoAndPlay(2);
missilez[k].stopListening();
var e:explosion = new explosion();
e.x = alienMissilez[j].x;
e.y = alienMissilez[j].y;
addChild(e);
score += 10;
}
}
}
}
function checkForMissileOnAlienMissile2()
{
var alienMissilez2:Array = new Array();
var missilez:Array = new Array();
for (var i=0;i<numChildren;i++)
{
if (getChildAt(i) is alienMissile2) {alienMissilez2.push(getChildAt(i) as MovieClip);}
if (getChildAt(i) is missile) {missilez.push(getChildAt(i) as MovieClip);}
}
trace("alienMissilez2" + alienMissilez2.length);
trace("missilez" + missilez.length);
for (var j=0;j<alienMissilez2.length;j++)
{
for (var k=0;k<missilez.length;k++)
{
if (alienMissilez2[j].hitTestObject(missilez[k]))
{
alienMissilez2[j].gotoAndPlay(2);
alienMissilez2[j].stopListening();
missilez[k].gotoAndPlay(2);
missilez[k].stopListening();
var e:explosion = new explosion();
e.x = alienMissilez2[j].x;
e.y = alienMissilez2[j].y;
addChild(e);
score += 15;
}
}
}
}
function checkForMissileOnAlienMissile3()
{
var alienMissilez3:Array = new Array();
var missilez:Array = new Array();
for (var i=0;i<numChildren;i++)
{
if (getChildAt(i) is alienMissile3) {alienMissilez3.push(getChildAt(i) as MovieClip);}
if (getChildAt(i) is missile) {missilez.push(getChildAt(i) as MovieClip);}
}
trace("alienMissilez3" + alienMissilez3.length);
trace("missilez" + missilez.length);
for (var j=0;j<alienMissilez3.length;j++)
{
for (var k=0;k<missilez.length;k++)
{
if (alienMissilez3[j].hitTestObject(missilez[k]))
{
alienMissilez3[j].gotoAndPlay(2);
alienMissilez3[j].stopListening();
missilez[k].gotoAndPlay(2);
missilez[k].stopListening();
var e:explosion = new explosion();
e.x = alienMissilez3[j].x;
e.y = alienMissilez3[j].y;
addChild(e);
score += 20;
}
}
}
}
/*function tidyUp()
{
for (var j=numChildren-1;j>=0;j--)
{
if (getChildAt(j) is TextField) continue; //This added to help text box work
var mc:MovieClip = getChildAt(j) as MovieClip;
if (getChildAt(j) is explosion)
{
if (mc.currentFrame==15) removeChildAt(j);
continue;
}
//if (mc.x>800 || mc.x<0 || mc.currentFrame!=1 ) removeChildAt(j);
}
}
*/
function tidyUp()
{
for (var j=numChildren-1;j>=0;j--)
{
if (getChildAt(j) is TextField) continue;
if (getChildAt(j) is SimpleButton) continue;
var mc:MovieClip = getChildAt(j) as MovieClip;
if (getChildAt(j) is explosion)
{
if (mc.currentFrame==10) removeChildAt(j);
//continue;
}
if (getChildAt(j) is alienMissile)
{
if (mc.x>800||(mc.currentFrame==10)) removeChildAt(j);
//continue;
}
if (getChildAt(j) is alienMissile2)
{
if (mc.x>800||(mc.currentFrame==10)) removeChildAt(j);
//continue;
}
if (getChildAt(j) is alienMissile3)
{
if (mc.x>800||(mc.currentFrame==10)) removeChildAt(j);
//continue;
}
if(getChildAt(j) is missile)
{
if(mc.x<0||(mc.currentFrame==2)) removeChildAt(j);
//continue;
}
if(getChildAt(j) is alien)
{
if(mc.currentFrame!=1) removeChildAt(j);
//continue;
}
if(getChildAt(j) is alien2)
{
if(mc.currentFrame!=1) removeChildAt(j);
//continue;
}
if(getChildAt(j) is alien3)
{
if(mc.currentFrame!=1) removeChildAt(j);
//continue;
}
}
}
function checkForAlienMissileOnSpaceship()
{
for (var i=0;i<numChildren;i++)
{
if (getChildAt(i) is alienMissile)
{
if (getChildAt(i).hitTestObject(mySpaceship))
{
var mc:MovieClip = getChildAt(i) as MovieClip;
if (mc.currentFrame==1)
{
mc.gotoAndPlay(2);
mc.stopListening();
var e:explosion = new explosion();
e.x = mc.x;
e.y = mc.y;
addChild(e);
mySpaceship.isHit();
}
}
}
}
}
function checkForAlienMissile2OnSpaceship()
{
for (var i=0;i<numChildren;i++)
{
if (getChildAt(i) is alienMissile2)
{
if (getChildAt(i).hitTestObject(mySpaceship))
{
var mc:MovieClip = getChildAt(i) as MovieClip;
if (mc.currentFrame==1)
{
mc.gotoAndPlay(2);
mc.stopListening();
var e:explosion = new explosion();
e.x = mc.x;
e.y = mc.y;
addChild(e);
mySpaceship.isHit();
}
}
}
}
}
function checkForAlienMissile3OnSpaceship()
{
for (var i=0;i<numChildren;i++)
{
if (getChildAt(i) is alienMissile3)
{
if (getChildAt(i).hitTestObject(mySpaceship))
{
var mc:MovieClip = getChildAt(i) as MovieClip;
if (mc.currentFrame==1)
{
mc.gotoAndPlay(2);
mc.stopListening();
var e:explosion = new explosion();
e.x = mc.x;
e.y = mc.y;
addChild(e);
mySpaceship.isHit();
}
}
}
}
}
stage.addEventListener (KeyboardEvent.KEY_DOWN, spaceshipControls);
function spaceshipControls (event:KeyboardEvent):void
{
if (event.keyCode==38 && mySpaceship.y>+62 && stage.frameRate==24) {mySpaceship.y-=20;}
if (event.keyCode==40 && mySpaceship.y<480-mySpaceship.height && stage.frameRate==24) {mySpaceship.y+=20;}
if (event.keyCode==32 && gameOn==true && stage.frameRate==24)
{
var m:missile = new missile();
m.y = mySpaceship.y;
m.x = mySpaceship.x - 80;
addChild(m);
my_channel = my_sound.play();
}
}
btn_up.addEventListener(MouseEvent.MOUSE_DOWN, goUp);
btn_up.addEventListener(MouseEvent.MOUSE_UP, stopMoving);
function goUp(evt:MouseEvent)
{
if (mySpaceship.y>+62 && stage.frameRate==24)
{
mySpaceship.y-=20;
}
else
{
spaceshipMovement=0;
}
}
function stopMoving (evt:MouseEvent)
{
spaceshipMovement=0;
}
btn_down.addEventListener(MouseEvent.MOUSE_DOWN, goDown);
btn_down.addEventListener(MouseEvent.MOUSE_UP, stopMoving2);
function goDown(evt:MouseEvent)
{
if (mySpaceship.y<480-mySpaceship.height && stage.frameRate==24)
{
mySpaceship.y+=20;
}
else
{
spaceshipMovement=0;
}
}
function stopMoving2 (evt:MouseEvent)
{
spaceshipMovement=0;
}
btn_fire.addEventListener(MouseEvent.MOUSE_DOWN, fire);
function fire(evt:MouseEvent)
{
var m:missile = new missile();
m.y = mySpaceship.y;
m.x = mySpaceship.x - 80;
addChild(m);
my_channel = my_sound.play();
}
function noLivesLeft()
{
stage.removeEventListener(KeyboardEvent.KEY_DOWN, spaceshipControls);
btn_fire.removeEventListener(MouseEvent.MOUSE_DOWN, fire);
flash.media.SoundMixer.stopAll();
my_channel3 = my_sound3.play();
removeEventListener(Event.ENTER_FRAME,pulse);
for (var i=0;i<numChildren;i++)
{
//trace(i);
if (getChildAt(i) is TextField) continue;
if (getChildAt(i) is SimpleButton) continue;
var mc:MovieClip = getChildAt(i) as MovieClip;
if (mc.hasEventListener(Event.ENTER_FRAME)) mc.stopListening();
}
gameOn = false;
mcGameOverScreen.visible = true;
mcGameOverScreen.tb_score.text = String (score);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, spaceshipControls);
btn_fire.removeEventListener(MouseEvent.MOUSE_DOWN, fire);
for (var c=numChildren-1;c>=0;c--)
{
var d = getChildAt(c);
if (d is alien || d is alienMissile|| d is explosion || d is missile || d is alien2 || d is alien3 ||d is alienMissile2 ||d is alienMissile3 || d is background) removeChildAt(c);
}
}
btnResume.addEventListener(MouseEvent.MOUSE_DOWN, resumeGame);
function resumeGame(e:MouseEvent):void
{
stage.frameRate = 24
btnPause.visible=true;
btnResume.visible=false;
}
btnPause.addEventListener(MouseEvent.MOUSE_DOWN, pauseGame);
function pauseGame(e:MouseEvent):void
{
stage.frameRate = 0
btnPause.visible=false;
btnResume.visible=true;
}
function setMute(vol)
{
var sTransform:SoundTransform = new SoundTransform(1,0);
sTransform.volume = vol;
SoundMixer.soundTransform = sTransform;
}
var isMuted:Boolean = false;
muteBtn.addEventListener(MouseEvent.CLICK,toggleMuteBtn);
function toggleMuteBtn(event:Event){
if(isMuted)
{
isMuted = false;
setMute(1);
}
else
{
isMuted = true;
setMute(0);
}
}
You are getting the error because you are checking for Alien3's parent before it has been added to the display list.
Add a trace before the parent.addChild(ao) line, ie:
trace("Alien3 parent = "+parent);
I'm betting the output will be null sometimes.
The solution is to replace the ENTER_FRAME event listener (in the Alien3 constructor function) with an ADDED_TO_STAGE event listener. Try this:
public function alien3() {
addEventListener(Event.ADDED_TO_STAGE, onStage);
}
private function onStage(e:Event):void {
removeEventListener(Event.ADDED_TO_STAGE, onStage);
addEventListener(Event.ENTER_FRAME, pulse);
}
Now, when pulse is called, 'parent' will not be null because the instance is on the display list and has access to 'parent'.

AS3: TypeError: Error #1009: Cannot access a property or method of a null object reference. Help Needed

I'm new to ActionScript and I really need help debugging this problem. This is what it says on my output when I run my code:
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at StreetHobogame_fla::MainTimeline/pickup()
at StreetHobogame_fla::MainTimeline/gameloop()
And this is my code:
import flash.events.KeyboardEvent;
stop();
guy.stop();
var enemySpeed:Number = 3;
var wspeed:Number = 0;
var vy:Number = 0;
var gv:Number = 1;
var jumped:Boolean = false;
var score:Number = 0;
var lives:Number = 5;
livesbox.text = lives.toString();
stage.addEventListener(Event.ENTER_FRAME,gameloop);
trace(ground.x);
var motionspeed:int = 30;
left.addEventListener(MouseEvent.MOUSE_DOWN, leftMove);
left.addEventListener(MouseEvent.MOUSE_UP, leftUp);
right.addEventListener(MouseEvent.MOUSE_DOWN, rightMove);
right.addEventListener(MouseEvent.MOUSE_UP, rightUp);
jumpButton.addEventListener(MouseEvent.MOUSE_DOWN, jumpPressed);
function jumpPressed(e:Event):void
{
if (! jumped)
{
vy = -14;
jumped = true;
}
}
function rightUp(e:Event):void
{
wspeed = 0;
}
function rightMove(e:Event):void
{
wspeed += 10;
guy.gotoAndStop(2);
}
function leftMove(event:Event):void
{
wspeed = -10;
guy.gotoAndStop(1);
}
function leftUp(event:Event):void
{
wspeed = 0;
}
function gameloop(e:Event)
{
moveplayer();
jumpgravity();
exitlevel1();
//exitlevel2();
pickup();
enemy();
spikes();
enemyMove();
return (0);
}
function pickup()
{
if (guy.hitTestObject(key))
{
key.visible = false;
}
if (guy.hitTestObject(coin1))
{
coin1.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin2))
{
coin2.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin3))
{
coin3.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin4))
{
coin4.x = 2000;
score++;
scorebox.text = score.toString();
}
}
function moveplayer()
{
guy.x += wspeed;
if (guy.x < 0)
{
guy.x = 0;
}
if (guy.x > 1024)
{
guy.x = 1024;
}
}
function jumpgravity()
{
vy += gv;
if (! ground.hitTestPoint(guy.x,guy.y,true))
{
guy.y += vy;
}
if (ground.hitTestPoint(guy.x,guy.y,true))
{
guy.y--;
vy = 0;
jumped = false;
}
}
function exitlevel1()
{
if (guy.hitTestObject(exitMC))
{
if (key.visible == false)
{
stage.removeEventListener(Event.ENTER_FRAME,gameloop);
left.removeEventListener(MouseEvent.MOUSE_DOWN, leftMove);
left.removeEventListener(MouseEvent.MOUSE_UP, leftUp);
right.removeEventListener(MouseEvent.MOUSE_DOWN, rightMove);
right.removeEventListener(MouseEvent.MOUSE_UP, rightUp);
jumped= false;
wspeed = 0;
guy.gotoAndStop(1);
gotoAndStop(1,"level1Questions");
}
}
}
/*function exitlevel2()
{
if (guy.hitTestObject(exit2MC))
{
if (key.visible == false)
{
jumped= false;
wspeed = 0;
guy.gotoAndStop(1);
gotoAndStop(1,"level2Complete");
}
}
}
*/
function enemy()
{
if (guy.hitTestObject(enemy1))
{
guy.x = 520.95;
guy.y = 425.50;
if (lives<=1)
{
lives = 0;
gotoAndStop(1,"GameOver");
}
else
{
lives--;
livesbox.text = lives.toString();
}
}
}
function spikes()
{
if (guy.hitTestObject(Spike))
{
guy.x = 520;
guy.y = 425.5;
if (lives<=1)
{
lives = 0;
gotoAndStop(1,"GameOver");
}
else
{
lives--;
livesbox.text = lives.toString();
}
}
}
function enemyMove():void
{
enemy1.x += enemySpeed;
if (enemy1.x >= 350)
{
enemySpeed *= -1;
enemy1.scaleX *= -1;
}
else if (enemy1.x < 60)
{
enemySpeed *= -1;
enemy1.scaleX *= -1;
}
}
Help would be much appreciated, thank you.
At least one of this variables are null when pickup() function executes:
guy
key
coin1
scorebox
coin2
coin3
coin4
You can use trace() function to check which one.
function pickup()
{
trace('guy==' + guy);
trace('key==' + key);
trace('scorebox==' + scorebox);
trace('coin1==' + coin1);
trace('coin2==' + coin2);
trace('coin3==' + coin3);
trace('coin4==' + coin4);
if (guy.hitTestObject(key))
{
key.visible = false;
}
if (guy.hitTestObject(coin1))
{
coin1.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin2))
{
coin2.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin3))
{
coin3.x = 2000;
score++;
scorebox.text = score.toString();
}
if (guy.hitTestObject(coin4))
{
coin4.x = 2000;
score++;
scorebox.text = score.toString();
}
}

as3 removeChild - I cannot target specific children

I'm still trying to get my head around AS3 and can't figure out how to target some specific Children in my project and remove them... I'm sure there's a simple solution to this on page 1 of a "Basic AS3" book somewhere but I can't work it out!
I'm trying to remove the red lines created in the addNewPoint function (or just give them an alpha of 0) as part of the fillDriveway function.
I can give you a link to the source files if you need.
Thanks so so much in advance!
Here's my terrible code:
import flash.display.*
pic.addEventListener(MouseEvent.CLICK,addNewPoint);
var n:Number = 0;
function addNewPoint(e:MouseEvent):void {
n++;
pointNo.text = String(n);
var nextPoint:MovieClip = new newPoint();
addChild(nextPoint);
nextPoint.name = "mc"+pointNo.text;
nextPoint.x = e.target.mouseX;
nextPoint.y = e.target.mouseY;
var joinPoints:MovieClip = new MovieClip();
this.addChild(joinPoints);
joinPoints.graphics.lineStyle(0.5,0xFF0000);
joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
for(var i:int=2; i<=n; ++i){
joinPoints.graphics.lineTo(this.getChildByName("mc"+i).x, this.getChildByName("mc"+i).y);
}
}
pic.addEventListener(MouseEvent.CLICK, addNewPoint);
function fillDriveway(eventObject:MouseEvent) {
var joinPoints:MovieClip = new MovieClip();
this.addChild(joinPoints);
joinPoints.graphics.beginFill(0xFFFFFF, 0.7);
joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
for(var m:int=2; m<=n; ++m){
joinPoints.graphics.lineTo(this.getChildByName("mc"+m).x, this.getChildByName("mc"+m).y);
}
joinPoints.name = "driveshape";
filledDrive.text = "filled";
}
function undoit(eventObject:MouseEvent) {
if(n > 0) {
if(filledDrive.text.indexOf("filled") != -1) {
this.removeChild(this.getChildAt(this.numChildren -1));
filledDrive.text = "";
}else{
this.removeChild(this.getChildAt(this.numChildren -1));
this.removeChild(this.getChildAt(this.numChildren -1));
n--;
pointNo.text = String(n);
}
}
}
undo.addEventListener(MouseEvent.CLICK, undoit);
function maskDrive(eventObject:MouseEvent) {
if(filledDrive.text.indexOf("filled") != -1) {
var finishA:MovieClip = new finishMC();
this.addChild(finishA);
finishA.x = 310;
finishA.y = 100;
finishA.mask = getChildByName("driveshape");
finishA.gotoAndPlay(2);
}
}
//BTN Actions
function btn1over(myEvent:MouseEvent) {
btn1.gotoAndPlay(2);
}
function btn1out(myEvent:MouseEvent) {
btn1.gotoAndPlay(11);
}
function btn2over(myEvent:MouseEvent) {
btn2.gotoAndPlay(2);
}
function btn2out(myEvent:MouseEvent) {
btn2.gotoAndPlay(11);
}
function btn3over(myEvent:MouseEvent) {
btn3.gotoAndPlay(2);
}
function btn3out(myEvent:MouseEvent) {
btn3.gotoAndPlay(11);
}
//BTN Calls
btn1.addEventListener(MouseEvent.CLICK, fillDriveway);
btn1.addEventListener(MouseEvent.ROLL_OVER, btn1over);
btn1.addEventListener(MouseEvent.ROLL_OUT, btn1out);
btn1.buttonMode = true;
btn1.useHandCursor = true;
btn2.addEventListener(MouseEvent.CLICK, maskDrive);
btn2.addEventListener(MouseEvent.ROLL_OVER, btn2over);
btn2.addEventListener(MouseEvent.ROLL_OUT, btn2out);
btn2.buttonMode = true;
btn2.useHandCursor = true;
btn3.buttonMode = true;
btn3.useHandCursor = true;
btn3.addEventListener(MouseEvent.ROLL_OVER, btn3over);
btn3.addEventListener(MouseEvent.ROLL_OUT, btn3out);
I think your issue is that each time you create a new joinPoints you are overwriting the pointer to the previous joinPoints instance, therefore you cannot access it. (this will create a memory leak).
Each time you create a joinPoints object, add it to an array:
joinPointsArray.push(joinPoints);
Your fillDriveway function can then access all the joinPoints you have created:
for (var i:int = 0; i < joinPointsArray.length, i++) {
joinPointsArray[i].alpha = 0;
}

as3 child as movieclip - won't accept functions

this follows on from my last question which I thought was answered but for some reason when I treat a child of my stage (display object) as a movieclip I can't then apply the usual functions that I want to:
var mc1:MovieClip = this.getChildByName("mc1") as MovieClip;
if(mc1) {
mc1.useHandCursor = true;
mc1.buttonMode = true;
mc1.addEventListener(MouseEvent.CLICK, fillDriveway);
}
Any wisdom would greatly appreciated... and sorry for asking such a similar question as previous...
Thanks in advance.
EDIT: More code from the AS on this project for context:
import flash.display.*
ImageUploader.visible = false;
function showUploader(e:MouseEvent):void {
ImageUploader.visible = true;
ImageUploader.gotoAndPlay(2);
}
pic.addEventListener(MouseEvent.CLICK,addNewPoint);
var n:Number = 0;
var joinPointsArray:Array = new Array;
function addNewPoint(e:MouseEvent):void {
n++;
pointNo.text = String(n);
if(n==1){
var nextPoint:MovieClip = new mcstart();
addChild(nextPoint);
nextPoint.name = "mc"+pointNo.text;
nextPoint.x = e.target.mouseX;
nextPoint.y = e.target.mouseY;
}else{
var nextPoint2:MovieClip = new newPoint();
addChild(nextPoint2);
nextPoint2.name = "mc"+pointNo.text;
nextPoint2.x = e.target.mouseX;
nextPoint2.y = e.target.mouseY;
}
var joinPoints:MovieClip = new MovieClip();
this.addChild(joinPoints);
joinPointsArray.push(joinPoints);
joinPoints.graphics.lineStyle(0.5,0xFF0000);
joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
for(var i:int=2; i<=n; ++i){
joinPoints.graphics.lineTo(this.getChildByName("mc"+i).x, this.getChildByName("mc"+i).y);
}
}
pic.addEventListener(MouseEvent.CLICK, addNewPoint);
function fillDriveway(eventObject:MouseEvent) {
var joinPoints:MovieClip = new MovieClip();
this.addChild(joinPoints);
for(var p:int=0; p<(joinPointsArray.length); ++p) {
joinPointsArray[p].alpha = 0;
}
this.getChildByName("mc1").alpha = 0;
joinPoints.graphics.beginFill(0xFFFFFF, 0.7);
joinPoints.graphics.moveTo(this.getChildByName("mc1").x, this.getChildByName("mc1").y);
for(var m:int=2; m<=n; ++m){
joinPoints.graphics.lineTo(this.getChildByName("mc"+m).x, this.getChildByName("mc"+m).y);
}
joinPoints.name = "driveshape";
filledDrive.text = "filled";
}
function undoit(eventObject:MouseEvent) {
if(n > 0) {
if(filledDrive.text.indexOf("filled") != -1) {
this.removeChild(this.getChildAt(this.numChildren -1));
filledDrive.text = "";
}else{
this.removeChild(this.getChildAt(this.numChildren -1));
this.removeChild(this.getChildAt(this.numChildren -1));
n--;
pointNo.text = String(n);
}
}
}
function maskDrive(eventObject:MouseEvent) {
if(filledDrive.text.indexOf("filled") != -1) {
var finishA:MovieClip = new finishMC();
this.addChild(finishA);
finishA.x = 310;
finishA.y = 100;
finishA.mask = getChildByName("driveshape");
finishA.gotoAndPlay(2);
}
}
//BTN RollOvers
function btn1over(myEvent:MouseEvent) {
btn1.gotoAndPlay(2);
}
function btn1out(myEvent:MouseEvent) {
btn1.gotoAndPlay(11);
}
function btn2over(myEvent:MouseEvent) {
btn2.gotoAndPlay(2);
}
function btn2out(myEvent:MouseEvent) {
btn2.gotoAndPlay(11);
}
function btn3over(myEvent:MouseEvent) {
btn3.gotoAndPlay(2);
}
function btn3out(myEvent:MouseEvent) {
btn3.gotoAndPlay(11);
}
function undoover(myEvent:MouseEvent) {
undo.gotoAndPlay(2);
}
function undoout(myEvent:MouseEvent) {
undo.gotoAndPlay(11);
}
//BTN Calls
btn1HIT.addEventListener(MouseEvent.CLICK, fillDriveway);
btn1HIT.addEventListener(MouseEvent.ROLL_OVER, btn1over);
btn1HIT.addEventListener(MouseEvent.ROLL_OUT, btn1out);
btn1HIT.buttonMode = true;
btn1HIT.useHandCursor = true;
btn2HIT.addEventListener(MouseEvent.CLICK, maskDrive);
btn2HIT.addEventListener(MouseEvent.ROLL_OVER, btn2over);
btn2HIT.addEventListener(MouseEvent.ROLL_OUT, btn2out);
btn2HIT.buttonMode = true;
btn2HIT.useHandCursor = true;
btn3HIT.buttonMode = true;
btn3HIT.useHandCursor = true;
btn3HIT.addEventListener(MouseEvent.ROLL_OVER, btn3over);
btn3HIT.addEventListener(MouseEvent.ROLL_OUT, btn3out);
btn3HIT.addEventListener(MouseEvent.CLICK, showUploader);
undoHIT.addEventListener(MouseEvent.CLICK, undoit);
undoHIT.addEventListener(MouseEvent.ROLL_OVER, undoover);
undoHIT.addEventListener(MouseEvent.ROLL_OUT, undoout);
undoHIT.buttonMode = true;
undoHIT.useHandCursor = true;
var mc1:MovieClip = this.getChildByName("mc1") as MovieClip;
if(mc1) {
mc1.useHandCursor = true;
mc1.buttonMode = true;
mc1.addEventListener(MouseEvent.CLICK, fillDriveway);
}
Are you sure the movieclip is placed on stage or actually converted to movieclip?
Try stage.getChildByName(). Where did you place this code? Inside a frame or inside a main document class? To be sure you can check the childs are added on stage and see what their names are.
You can use this code
for ( var i :int = 0; i < this.numChildren; i++ )
{
babe = this.getChildAt( i );
if ( babe is MovieClip) {
trace( babe.name);
}
}
I've also seen this, not sure if it works.
if (stage.contains(mc1)) {
}
Wahoo! Figured it out!
By popping
var mc1:MovieClip = this.getChildByName("mc1") as MovieClip;
at the end of my AS I was referring to the child "mc1" before it existed - it isn't created until the user clicks somewhere on the "pic" movieclip. So the solution was to bung my actions for "mc1" (including declaring it as a MovieClip) into a separate function:
function createstartEndMC():void {
var startEnd:MovieClip = (this.getChildByName("mc1")) as MovieClip;
startEnd.useHandCursor = true;
startEnd.buttonMode = true;
startEnd.addEventListener(MouseEvent.CLICK, fillDriveway);
}
and then to call this function AFTER "mc1" child is created:
function addNewPoint(e:MouseEvent):void {
n++;
pointNo.text = String(n);
if(n==1){
var nextPoint:MovieClip = new mcstart();
addChild(nextPoint);
nextPoint.name = "mc"+pointNo.text;
nextPoint.x = e.target.mouseX;
nextPoint.y = e.target.mouseY;
createstartEndMC();
}
Finally it works and "mc1" (or "startEnd" as I call it once it's created and made into an MC) finally behaves as a normal timeline MC should!
I'm so happy - thanks for all your guidance!
Cam