How can I use a function parameter to refer to a variable? - actionscript-3

Sorry if this question is a bit vague, but this has been driving me nuts recently. It's nothing too complicated, but all I want to do is have the variable 'targetVariable' be affected by a formula. The actual problem lies in the fact that the referenced variable, being 'masterVolume' in this case, is not getting affected by the formula, but rather 'targetVariable' instead. I run the 'makeSlider' function at the bottom of the script. Here's the code:
var masterVolume:Number = 0;
var panning:Number = 0;
function makeSlider(sliderType, X, Y, targetVariable) {
var sliderHandle:MovieClip = new sliderType();
addChild(sliderHandle);
sliderHandle.x = X;
sliderHandle.y = Y;
var dragging:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, updateSlider);
function updateSlider(e:Event):void {
panning = (mouseX/(stage.stageWidth/2))-1;
targetVariable = ((sliderHandle.x-bar.x)/bar.width);
output.text = masterVolume.toString();
if (dragging == true && mouseX >= bar.x && mouseX <= (bar.x + bar.width)) {
sliderHandle.x = mouseX;
}
}
sliderHandle.addEventListener(MouseEvent.MOUSE_DOWN, beginDrag);
function beginDrag(e:MouseEvent):void {
dragging = true;
}
stage.addEventListener(MouseEvent.MOUSE_UP, endDrag);
function endDrag(e:MouseEvent):void {
dragging = false;
}
}
function playSound(target, intensity:Number, pan:Number) {
var sound:Sound = new target();
var transformer:SoundTransform = new SoundTransform(intensity, pan);
var channel:SoundChannel = new SoundChannel();
channel=sound.play();
channel.soundTransform = transformer;
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, make);
function make(e:MouseEvent):void {
playSound(test, masterVolume, panning);
}
makeSlider(SliderHandle, bar.x, bar.y, masterVolume);

Okay, so I studied the Object class and found out that I could reference the variable by making it an object in the function. Here's the updated, working script:
var panning:Number = 0;
var masterVolume:Number = 0;
function makeSlider(sliderType, barType, soundType, hitBoxScale:Number, X, Y, targetVariable) {
var reference:Object = { targetVariable: 0 };
var slider:MovieClip = new sliderType;
var newBar:MovieClip = new barType;
addChild(newBar);
newBar.x = X;
newBar.y = Y;
addChild(slider);
slider.x = X;
slider.y = Y;
var dragging:Boolean = false;
stage.addEventListener(Event.ENTER_FRAME, updateSlider);
function updateSlider(e:Event):void {
panning = (mouseX/(stage.stageWidth/2))-1;
reference.targetVariable = (slider.x-newBar.x)/newBar.width;
if (dragging == true && mouseX >= newBar.x && mouseX <= (newBar.x + newBar.width)) {
slider.x = mouseX;
}
if (reference.targetVariable <= 0.01) {
output.text = ("None");
}
if (reference.targetVariable >= 0.99) {
output.text = ("Max");
}
if (reference.targetVariable > 0.01 && reference.targetVariable < 0.99) {
output.text = (Math.round((reference.targetVariable*100))+"%").toString();
}
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, beginDrag);
function beginDrag(e:MouseEvent):void {
if (mouseY >= newBar.y-hitBoxScale && mouseY <= (newBar.y + newBar.height)+hitBoxScale) {
dragging = true;
}
}
slider.addEventListener(MouseEvent.MOUSE_DOWN, beginDragFromSlider);
function beginDragFromSlider(e:MouseEvent):void {
dragging = true;
}
stage.addEventListener(MouseEvent.MOUSE_UP, endDrag);
function endDrag(e:MouseEvent):void {
if (dragging == true) {
playSound(soundType, reference.targetVariable, 0);
}
dragging = false;
}
stage.addEventListener(MouseEvent.MOUSE_DOWN, make);
function make(e:MouseEvent):void {
if (dragging == false) {
playSound(test, reference.targetVariable, panning);
}
}
}
function playSound(target, intensity:Number, pan:Number) {
var sound:Sound = new target();
var transformer:SoundTransform = new SoundTransform(intensity, pan);
var channel:SoundChannel = new SoundChannel();
channel=sound.play();
channel.soundTransform = transformer;
}
makeSlider(defaultSlider, defaultBar, volumeIndicator, 10, 134, 211, masterVolume);

Related

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'.

User interaction with Leapmotion AS3 library

I can connect the device and attach a custom cursor to one finger, but I can´t use any of the gestures to over/click a button or drag a sprite around, etc.
I´m using Starling in the project. To run this sample just create a Main.as, setup it with Starling and call this class.
My basic code:
package
{
import com.leapmotion.leap.Controller;
import com.leapmotion.leap.events.LeapEvent;
import com.leapmotion.leap.Finger;
import com.leapmotion.leap.Frame;
import com.leapmotion.leap.Gesture;
import com.leapmotion.leap.Hand;
import com.leapmotion.leap.InteractionBox;
import com.leapmotion.leap.Pointable;
import com.leapmotion.leap.ScreenTapGesture;
import com.leapmotion.leap.Vector3;
import starling.display.Shape;
import starling.display.Sprite;
import starling.events.Event;
import starling.events.TouchEvent;
/**
* ...
* #author miau
*/
public class LeapController extends Sprite
{
private var _controller:Controller;
private var _cursor:Shape;
private var _screenTap:ScreenTapGesture;
private var _displayWidth:uint = 800;
private var _displayHeight:uint = 600;
public function LeapController()
{
addEventListener(Event.ADDED_TO_STAGE, _startController);
}
private function _startController(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, _startController);
//adding controller
_controller = new Controller();
_controller.addEventListener( LeapEvent.LEAPMOTION_INIT, onInit );
_controller.addEventListener( LeapEvent.LEAPMOTION_CONNECTED, onConnect );
_controller.addEventListener( LeapEvent.LEAPMOTION_DISCONNECTED, onDisconnect );
_controller.addEventListener( LeapEvent.LEAPMOTION_EXIT, onExit );
_controller.addEventListener( LeapEvent.LEAPMOTION_FRAME, onFrame );
//add test button
_testButton.x = stage.stageWidth / 2 - _testButton.width / 2;
_testButton.y = stage.stageHeight / 2 - _testButton.height / 2;
addChild(_testButton);
_testButton.touchable = true;
_testButton.addEventListener(TouchEvent.TOUCH, doSomething);
//draw ellipse as a cursor
_cursor = new Shape();
_cursor.graphics.lineStyle(6, 0xFFE24F);
_cursor.graphics.drawEllipse(0, 0, 80, 80);
addChild(_cursor);
}
private function onFrame(e:LeapEvent):void
{
trace("ON FRAME STARTED");
var frame:Frame = e.frame;
var interactionBox:InteractionBox = frame.interactionBox;
// Get the first hand
if(frame.hands.length > 0){
var hand:Hand = frame.hands[0];
var numpointables:int = e.frame.pointables.length;
var pointablesArray:Array = new Array();
if(frame.pointables.length > 0 && frame.pointables.length < 2){
//trace("number of pointables: "+frame.pointables[0]);
for(var j:int = 0; j < frame.pointables.length; j++){
//var pointer:DisplayObject = pointablesArray[j];
if(j < numpointables){
var pointable:Pointable = frame.pointables[j];
var normal:Vector3 = pointable.tipPosition;
var normalized:Vector3 = interactionBox.normalizePoint(normal);
//pointable.isFinger = true;
_cursor.x = normalized.x * _displayWidth;
_cursor.y = _displayHeight - (normalized.y * _displayHeight);
_cursor.visible = true;
}else if (j == 0) {
_cursor.visible = false;
}
}
}
}
}
private function onExit(e:LeapEvent):void
{
trace("ON EXIT STARTED");
}
private function onDisconnect(e:LeapEvent):void
{
trace("ON DISCONNECT STARTED");
}
private function onConnect(e:LeapEvent):void
{
trace("ON CONNECT STARTED");
_controller.enableGesture( Gesture.TYPE_SWIPE );
_controller.enableGesture( Gesture.TYPE_CIRCLE );
_controller.enableGesture( Gesture.TYPE_SCREEN_TAP );
_controller.enableGesture( Gesture.TYPE_KEY_TAP );
}
private function onInit(e:LeapEvent):void
{
trace("ON INIT STARTED");
}
private function doSomething(e:TouchEvent):void
{
trace("I WAS TOUCHED!!!");
}
}
}
If a good code Samaritan can update this code to perform a screen tap gesture (or any interacion with any object), I will really appreciate this a lot.
Regards!
controller.enableGesture(Gesture.TYPE_SWIPE);
controller.enableGesture(Gesture.TYPE_SCREEN_TAP);
if(controller.config().setFloat("Gesture.Swipe.MinLength", 200.0) && controller.config().setFloat("Gesture.Swipe.MinVelocity", 500)) controller.config().save();
if(controller.config().setFloat("Gesture.ScreenTap.MinForwardVelocity", 30.0) && controller.config().setFloat("Gesture.ScreenTap.HistorySeconds", .5) && controller.config().setFloat("Gesture.ScreenTap.MinDistance", 1.0)) controller.config().save();
//etc...
Then catch it in the frame event listener:
private function onFrame( event:LeapEvent ):void
{
var frame:Frame = event.frame;
var gestures:Vector.<Gesture> = frame.gestures();
for ( var i:int = 0; i < gestures.length; i++ )
{
var gesture:Gesture = gestures[ i ];
switch ( gesture.type )
{
case Gesture.TYPE_SCREEN_TAP:
var screentap:ScreenTapGesture = ScreenTapGesture ( gesture);
trace ("ScreenTapGesture-> x: " + Math.round(screentap.position.x ) + ", y: "+ Math.round( screentap.position.y));
break;
case Gesture.TYPE_SWIPE:
var screenSwipe:SwipeGesture = SwipeGesture(gesture);
if(gesture.state == Gesture.STATE_START) {
//
}
else if(gesture.state == Gesture.STATE_STOP) {
//
trace("SwipeGesture-> direction: "+screenSwipe.direction + ", duration: " + screenSwipe.duration);
}
break;
default:
trace( "Unknown gesture type." )
}
}
}
When the event occurs, check the coordinates translated to the stage/screen and whether a hit test returns true.
EDIT: Considering I have no idea how to reliable get the touch point x/y (or better: how to translate them to the correct screen coordinates), I would probably do something like this in my onFrame event:
private function onFrame(event:LeapEvent):void {
var frame:Frame = event.frame;
var gestures:Vector.<Gesture> = frame.gestures();
var posX:Number;
var posY:Number;
var s:Shape;
if(frame.pointables.length > 0) {
var currentVector:Vector3 = screen.intersectPointable(frame.pointables[0], true); //get normalized vector
posX = 1920 * currentVector.x - stage.x; //NOTE: I hardcoded the screen res value, you can get it like var w:int = leap.locatedScreens()[0].widthPixels();
posY = 1080 * ( 1 - currentVector.y ) - stage.y; //NOTE: I hardcoded the screen res value, you can get it like var h:int = leap.locatedScreens()[0].heightPixels();
}
for(var i:int = 0; i < gestures.length; i++) {
var gesture:Gesture = gestures[i];
if(gesture.type == Gesture.TYPE_SCREEN_TAP) {
if(posX >= _button1.x &&
posX <= _button1.x + _button1.width &&
posY >= _button1.y &&
posY <= _button1.y + _button1.height) {
s = new Shape();
s.graphics.beginFill(0x00FF00);
s.graphics.drawCircle(0, 0, 10);
s.graphics.endFill();
s.x = posX;
s.y = posY;
stage.addChild(s);
trace("Lisa tocada!");
}
else {
s = new Shape();
s.graphics.beginFill(0xFF0000);
s.graphics.drawCircle(0, 0, 10);
s.graphics.endFill();
s.x = posX;
s.y = posY;
stage.addChild(s);
trace("Fallaste! Intentalo otra vez, tiempo: "+new Date().getTime());
}
}
}
}

HTML5, Easel.js game problems

Been working on an easel game tutorial that involves an animated character going across the screen and avoiding crates falling from above. I've followed the code in the tutorial exactly but no joy;nothing seems to be loading (including images which are mapped correctly). No errors regarding syntax seem to occur so not sure what the problem is. It's a fair bit of code so totally understand if no-one has the time but just in case here it is ;
Site Page code (ill post the individual JavaScript file codes if anyone is interested;
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<style>
body {
background-color: #000;
}
</style>
<script src="lib/easeljs-0.6.0.min.js"></script>
<script src="JS/Platform.js"></script>
<script src="JS/Hero.js"></script>
<script src="JS/Crate.js"></script>
<script>
var KEYCODE_SPACE = 32, KEYCODE_LEFT = 37, KEYCODE_RIGHT = 39;
var canvas, stage, lfheld, rtheld, platforms, crates, hero, heroCenter, key, door, gameTxt;
var keyDn = false, play=true, dir="right";
var loaded = 0, vy = 0, vx = 0;
var jumping = false, inAir = true, gravity = 2;
var img = new Image();
var bgimg = new Image();
var kimg = new Image();
var dimg = new Image();
var platformW = [300, 100, 180, 260, 260, 100, 100];
var platformX = [40, 220, 320, 580, 700, 760, 760];
var platformY = [460, 380, 300, 250, 550, 350, 450];
document.onkeydown=handleKeyDown;
document.onkeyup=handleKeyUp;
function init(){
canvas = document.getElementById("canvas");
stage = new createjs.Stage(canvas);
bgimg.onload = this.handleImageLoad;
bgimg.src = "img/scene.jpg";
kimg.onload = this.handleImageLoad;
kimg.src="img/key.png";
dimg.onload = this.handleImageLoad;
dimg.src = "img/door.jpg";
img.onload = this.handleImageLoad;
img.src = "img/hero.png";
}
function handleImageLoad(event) {
loaded+=1;
if (loaded==4){
start();
}
}
function handleKeyDown(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = true;
dir="left"; break;
case KEYCODE_RIGHT: rtHeld = true;
dir="right"; break;
case KEYCODE_SPACE: jump(); break;
}
}
function handleKeyUp(e) {
if(!e){ var e = window.event; }
switch(e.keycode) {
case KEYCODE_LEFT: lfHeld = false;
keyDn=false; hero.gotoAndStop("idle_h"); break;
case KEYCODE_RIGHT: rtHeld = false;
keyDn=false; hero.gotoAndStop("idle"); break;
}
}
function start(){
var bg = new createjs.Bitmap(bgimg);
stage.addChild(bg);
door = new createjs.Bitmap(dimg);
door.x = 131;
door.y = 384;
stage.addChild(door);
hero = new Hero(img);
hero.x = 80;
hero.y = 450;
stage.addChild(Hero);
crates = new Array();
paltforms = new Array();
for(i=0; i < platformW.length; i++){
var platform = new Platform(platformW[i],20);
platforms.push(platform);
stage.addChild(platform);
platform.x = platformX[i];
platform.y = platformY[i];
}
for(j=0; j < 5; j++){
var crate = new Crate();
crates.push(crate);
stage.addChild(crate);
resetCrates(crate);
}
key = new createjs.Bitmap(kimg);
key.x = 900;
key.y = 490;
stage.addChild(key);
Ticker.setFPS(30);
Ticker.addListener(window);
stage.update();
}
function tick() {
heroCenter = hero.y-40;
if (play){
vy+=gravity;
if (inAir){
hero.y+=vy;
}
if (vy>15){
vy=15;
}
for(i=0; i < platforms.length; i++){
if (hero.y >= platforms[i].y && hero.y<=(platforms[i].y+platforms[i].height) && hero.x>
platforms[i].x && hero.x<(platforms[i].
x+platforms[i].width)){;
hero.y=platforms[i].y;
vy=0;
jumping = false;
inAir = false;
break;
}else{
inAir = true;
}
}
for(j=0; j < crates.length; j++){
var ct = crates[j];
ct.y+=ct.speed;
ct.rotation+=3;
if (ct.y>650){
resetCrates(ct);
}
if (collisionHero (ct.x, ct.y, 20)){
gameOver();}
}
if (collisionHero (key.x+20, key.y+20,
20)){
key.visible=false;
door.visible=false;
}
if (collisionHero (door.x+20, door.y+40,
20) && key.visible==false){nextLevel();}
if (lfHeld){vx = -5;}
if (rtHeld){vx = 5;}
if(lfHeld && keyDn==false && inAir==false)
{
hero.gotoAndPlay("walk_h");
keyDn=true;
}
if(rtHeld && keyDn==false &&
inAir==false){
hero.gotoAndPlay("walk");
keyDn=true;
}
if (dir=="left" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle_h");
}
if (dir=="right" && keyDn==false &&
inAir==false){
hero.gotoAndStop("idle");
}
hero.x+=vx;
vx=vx*0.5;
if (hero.y>610){
gameOver();
}
}
stage.update();
}
function end(){
play=false;
var l = crates.length;
for (var i=0; i<l; i++){
var c = crates[i];
resetCrates(c);
}
hero.visible=false;
stage.update();
}
function nextLevel(){
gameTxt = new createjs.Text("Well Done\n\n",
"36px Arial", "#000");
gameTxt.text += "Prepare for Level 2";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
}
function gameOver(){
gameTxt = new createjs.Text("Game Over\n\n",
"36px Arial", "#000");
gameTxt.text += "Click to Play Again.";
gameTxt.textAlign = "center";
gameTxt.x = canvas.width / 2;
gameTxt.y = canvas.height / 4;
stage.addChild(gameTxt);
end();
canvas.onclick = handleClick;
}
function handleClick() {
canvas.onclick = null;
hero.visible=true;
hero.x = 80;
hero.y = 450;
door.visible=true;
key.visible=true;
stage.removeChild(gameTxt);
play=true;
}
function collisionHero (xPos, yPos,
Radius){
var distX = xPos - hero.x;
var distY = yPos - heroCenter;
var distR = Radius + 20;
if (distX * distX + distY * distY <=
distR * distR){
return true;
}
}
function jump(){
if (jumping == false && inAir == false){
if (dir=="right"){
hero.gotoAndStop("jump");
}else{
hero.gotoAndStop("jump_h");
}
hero.y -=20;
vy = -25;
jumping = true;
keyDn=false;
}
}
function resetCrates(crt) {
crt.x = canvas.width * Math.random()|0;
crt.y = 0 - Math.random()*500;
crt.speed = (Math.random()*5)+8;
}
</script>
<title>Game</title>
</head>
<body onload="init();">
<canvas id="canvas" width="960px" height="600px"></canvas>
</body>
</html>
Adding the js files as listed in the header.
Platform.js:
(function(window) {
function Platform(w,h) {
this.width = w;
this.height = h;
this.initialize();
}
Platform.prototype = new createjs.Container ();
Platform.prototype.platformBody = null;
Platform.prototype.Container_initialize = Platform.prototype.initialize;
Platform.prototype.initialize = function() {
this.Container_initialize();
this.platformBody = new createjs.Shape();
this.addChild(this.platformBody);
this.makeShape();
}
Platform.prototype.makeShape = function() {
var g = this.platformBody.graphics;
g.drawRect(0,0,this.width,this.height);
}
window.Platform = Platform;
}(window));
Hero.js
(function(window) {
function Hero(imgHero) {
this.initialize(imgHero);
}
Hero.prototype = new createjs.BitmapAnimation();
Hero.prototype.Animation_initialize = Hero.prototype.initialize;
Hero.prototype.initialize = function(imgHero) {
var spriteSheet = new createjs.SpriteSheet({
images: [imgHero],
frames: {width: 60, height: 85, regX: 29, regY: 80}, animations: {
walk: [0, 19, "walk"],
idle: [20, 20],
jump: [21, 21] } });
SpriteSheetUtils
.addFlippedFrames(spriteSheet, true, false,
false);
this.Animation_initialize(spriteSheet);
this.gotoAndStop("idle");
}
window.Hero = Hero;
}(window));
Crate.js
(function(window) {
function Crate() {
this.initialize();
}
Crate.prototype = new createjs.Container();
Crate.prototype.img = new Image();
Crate.prototype.Container_initialize =
Crate.prototype.initialize;
Crate.prototype.initialize = function() {
this.Container_initialize();
var bmp = new createjs.Bitmap("img/crate.jpg");
bmp.x=-20;
bmp.y=-20;
this.addChild(bmp);}
window.Crate = Crate;
}(window));
I noticed that you try to initialize the EaselJS-objects without a namespace:
stage = new Stage(canvas);
But since 0.5.0 you have to use the createjs-namespace(or map the namespace to window before you do anything)
So what you would have to do now will ALL easelJS-classes is to add a createjs. before them when you are creating a new instance like this:
stage = new createjs.Stage(canvas);
Not sure if that's everything, but it's a start, hope this helps.
You can read more on CreateJS namepsacing here: https://github.com/CreateJS/EaselJS/blob/master/README_CREATEJS_NAMESPACE.txt

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