Is anyone interested in looking at my code for a game? I'm getting strange errors - actionscript-3

I'm trying to make my first real, simple shooter game. I've read through tutorials online and instead of directly copying code, I tried to take things the next level to actually understand the code and add my own twists. With this in mind, I've recently been learning arrays and not sure if I am using them correctly.
I'm getting strange, intermittent
Error #2025 DisplayObject must be a child of the caller
messages in the output window, not the compiler window.
So, I don't know what line of code is generating this problem. By commenting out blocks of code I have narrowed it down to the modules labeled "CLEANUP MISSED ENEMIES" and "BULLET RATE OF SHOOTING", but the 'why' is beyond my understanding.
I am sure there will be many great comments pointing out conventions I get wrong and errors I am making. I value every chance to learn so please give your input as you see fit! I bet there are way better methods to do the things I am doing!
package{
import flash.events.Event;
import flash.display.MovieClip;
import flash.media.Sound;
import flash.media.SoundChannel;
import com.greensock.*;
import com.greensock.easing.*;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.geom.ColorTransform;
import fl.motion.Color;
import flash.display.DisplayObject;
public class chopper extends MovieClip{
public function chopper(){
boot();
}
public function boot():void{
/////////VARS
var coptr:MovieClip = new copter();
var bulit:MovieClip = new bullit();
var mouseIsDn = false;
var speed = 0;
var PEW = false
var meter:MovieClip = new meters();
var bltArray:Array = new Array();
var airArray:Array = new Array();
var gndArray:Array = new Array();
var gameTIMERa:Timer = new Timer(5000);
var gameTIMERb:Timer = new Timer(10000);
stage.addEventListener(MouseEvent.MOUSE_DOWN, clicked);
stage.addEventListener(MouseEvent.MOUSE_UP, unclicked);
function clicked(e:Event):void{
mouseIsDn = true;
}
function unclicked(e:Event):void{
mouseIsDn = false;
}
/////////INTRO SCREEN
var titl:MovieClip = new title();
addChild(titl);
var strt:MovieClip = new start();
addChild(strt);
var govr:MovieClip = new gOVER();
var ctINTRO:Color = new Color();
ctINTRO.setTint(Math.random()*0xFFFFFF, 0.5);
BG.transform.colorTransform = ctINTRO;
/////////MUSIC
var ChanAB:SoundChannel = new SoundChannel();
var Amusic:Sound = new musicA();
var Bmusic:Sound = new musicB();
ChanAB = Amusic.play(0, 9999);
/////////SFx
var ChanSFx:SoundChannel = new SoundChannel();
var Ashoot:Sound = new shootA();
var SFx:Array = new Array();
var Asuck:Sound = new suckA();
SFx.push(Asuck);
var Bsuck:Sound = new suckB();
SFx.push(Bsuck);
var Csuck:Sound = new suckC();
SFx.push(Csuck);
var gOver:Sound = new over();
/////////START
strt.startBTN.addEventListener(MouseEvent.CLICK, str);
function str(e:Event):void{
removeChild(titl);
removeChild(strt);
ChanAB.stop();
BG.transform.colorTransform = new ColorTransform;
////////////
ChanAB = Bmusic.play(0, 9999);
addChild(coptr);
TweenLite.to(coptr, 3, {x:157, y:316});
addChild(meter);
meter.x = 861;
meter.y = 9;
TweenLite.to(meter, 1, {x:735});
meter.life.gotoAndPlay(2);
gameTIMERa.addEventListener(TimerEvent.TIMER, addAIR);
gameTIMERa.start();
gameTIMERb.addEventListener(TimerEvent.TIMER, addGND);
gameTIMERb.start();
}
/////////ADDING ENEMIES
function addAIR(e:TimerEvent):void{
var Aair:MovieClip = new airA();
Aair.x = 805;
Aair.scaleX = .25
Aair.y = Math.random() * stage.stageHeight - Aair.height;
Aair.scaleY = .25
airArray.push(Aair);
addChild(Aair);
}
function addGND(e:TimerEvent):void{
var Agnd:MovieClip = new gndA();
Agnd.x = 805;
Agnd.scaleX = .25
Agnd.y = 430 + Math.floor(Math.random() * 36);
Agnd.scaleY = .25
gndArray.push(Agnd);
addChild(Agnd);
}
addEventListener(Event.ENTER_FRAME, startLoop);
function startLoop(e:Event):void{
if(coptr.x == 157 && coptr.y == 316){
speed = 10;
meter.life.gotoAndStop(10);
removeEventListener(Event.ENTER_FRAME, startLoop);
addEventListener(Event.ENTER_FRAME, gameLoop);
stage.addEventListener(KeyboardEvent.KEY_DOWN, shoot);
}
}
/////////COPTER SHOOTING
function shoot(e:Event):void{
if(PEW == false){
ChanSFx = Ashoot.play();
bulit.x = coptr.x + 5;
bulit.y = coptr.y;
bltArray.push(bulit);
addChild(bulit);
PEW = true;
}
}
/////////LIFE METER
function lifeMeterA(e:Event = null):void{
if(meter.life.width > 59){
meter.life.scaleX -= .04;
}
else if(meter.life.width < 59 && meter.life.width > 29){
meter.life.gotoAndStop(11);
meter.life.scaleX -= .04;
}
else if(meter.life.width < 29 && meter.life.width > 15){
meter.life.gotoAndStop(12)
meter.life.scaleX -= .04;
}
else if(meter.life.width < 15 && meter.life.width > 1.5){
meter.life.gotoAndPlay(2);
meter.life.scaleX -= .04;
}
}
function lifeMeterB(e:Event = null):void{
if(meter.life.width > 59){
meter.life.scaleX -= .01;
}
else if(meter.life.width < 59 && meter.life.width > 29){
meter.life.gotoAndStop(11);
meter.life.scaleX -= .01;
}
else if(meter.life.width < 29 && meter.life.width > 15){
meter.life.gotoAndStop(12)
meter.life.scaleX -= .01;
}
else if(meter.life.width < 15 && meter.life.width > 1.5){
meter.life.gotoAndPlay(2);
meter.life.scaleX -= .01;
}
}
////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////MAIN LOOP
function gameLoop(e:Event) {
////////////////////////COPTER MOVEMENT
trace(bltArray);
trace(airArray);
trace(gndArray);
coptr.y += speed;
if(mouseIsDn){
if(speed > -5){
speed -= 1;
}
}else{
if(speed < 10){
speed += .25;
}
}
////////////////////////BULLET MOVEMENT
if(bulit){
bulit.x += 10;
}
if(coptr.y > stage.stageHeight - coptr.height*.5){
coptr.y = stage.stageHeight - coptr.height*.5;
}
else if(coptr.y < 0 + coptr.height*.5){
coptr.y = 0 + coptr.height*.5;
}
////////////////////////COLLISIONS
for(var i = 0; i<numChildren; i++){
if(getChildAt(i) is airA){
var b = getChildAt(i) as airA;
if(b.hitTestObject(coptr)){
lifeMeterA();
}
if(b.hitTestObject(bulit)){
airArray.shift();
removeChild(b);
removeChild(bltArray[0]);
PEW = false;
var m:uint = uint(Math.random() * 3);
ChanSFx = SFx[m].play();
}
}
else if(getChildAt(i) is gndA){
var c = getChildAt(i) as gndA;
if(c.hitTestObject(coptr)){
lifeMeterB();
}
if(c.hitTestObject(bulit)){
gndArray.shift();
removeChild(c);
removeChild(bltArray[0]);
PEW = false;
var n:uint = uint(Math.random() * 3);
ChanSFx = SFx[n].play();
}
}
}
if(coptr.y > stage.stageHeight - coptr.height){
lifeMeterA();
}
////////////////////////CLEANUP MISSED ENEMIES
if(airArray[0] && airArray[0].x < 0){
airArray.shift();
}
if(gndArray[0] && gndArray[0].x < 0){
gndArray.shift();
}
////////////////////////BULLET RATE OF SHOOTING
if(bltArray[0] && bltArray[0].x > stage.stageWidth){
PEW = false;
bltArray.shift();
}
////////////////////////END GAME
if(meter.life.width < 1.5){
removeEventListener(Event.ENTER_FRAME, gameLoop);
gameTIMERa.stop();
gameTIMERb.stop();
meter.life.gotoAndStop(13);
TweenLite.to(meter, .5, {x:861});
gameO();
}
}
function gameO(e:Event = null):void{
addChild(govr);
govr.x = 0;
govr.y = 0;
ChanAB.stop();
ChanSFx = gOver.play();
ChanSFx.addEventListener(Event.SOUND_COMPLETE, restart);
}
function restart(e:Event):void{
removeChild(govr);
removeChild(coptr);
boot();
}
}
}
}
Thanks in advance!

It means you're using removeChild() somewhere on an object whose parent is not the container you are trying to remove it from.
For example, this code would cause that error:
var shape:Shape = new Shape();
stage.removeChild(shape);
It's likely that you are calling removeChild() more than once somewhere in your code.

Related

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());
}
}
}
}

1046 AS3 Compile Time Error

I'm having major issues with this one error
//Obligitory Stop
stop();
//Imports
import flash.events.Event;
import flash.events.KeyboardEvent;
import fl.motion.easing.Back;
import flash.events.MouseEvent;
import flash.accessibility.Accessibility;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.display.MovieClip;
//Variables
var bulletSpeed:uint = 20;
var scoreData:int;
var bullets:Array = new Array();
var killCounter:int;
var baddieCounter:int;
var currentLevel:int = 1;
var baddieDamage:int;
var energyCost:int;
var target:MovieClip;
var baddies:Array = new Array();
var timer:Timer = new Timer(1);
var baddieSpeed:int;
var score:int;
var levelKR:int;
var level1KR:int = 10;
var level2KR:int = 25;
var level3KR:int = 50;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var Baddie:MovieClip
var mySound:Sound = new ShootSFX();
//Level Atributes set
if (currentLevel == 1)
{
baddieSpeed = 2;
baddieDamage = 20;
timer.delay = 4000;
levelKR = level1KR;
bulletSpeed = 10;
energyCost = 50;
var energyTimer:Timer = new Timer(50);
var healthTimer:Timer = new Timer(1000);
}
//Event Listeners
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
rbDash.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
//Timers Start
timer.start();
energyTimer.start();
healthTimer.start();
//Initialize score
Score.text = String("Level "+currentLevel+" - begin!");
//load score data
score = scoreData;
//Checks Kill Counter
checkKillCounter();
//Shoot gun on space
function fireGun(evt:KeyboardEvent)
{
if (evt.keyCode == Keyboard.SPACE)
{
bullet.x = rbDash.x;
bullet.y = rbDash.y + 50;
addChild(bullet);
bullets.push(bullet);
}
}
//Move Objects
function moveObjects(evt:Event):void
{
moveBullets();
moveBaddies();
}
//Move bullets
function moveBullets():void
{
for (var i:int = 0; i < bullets.length; i++)
{
var dx = Math.cos(deg2rad(bullets[i].rotation)) * bulletSpeed;
var dy = Math.sin(deg2rad(bullets[i].rotation)) * bulletSpeed;
bullets[i].x += dx;
bullets[i].y += dy;
if (bullets[i].x <-bullets[i].width
|| bullets[i].x > stage.stageWidth + bullets[i].width
|| bullets[i].y < -bullets[i].width
|| bullets[i].y > stage.stageHeight + bullets[i].width)
{
removeChild(bullets[i]);
bullets.splice(i, 1);
}
}
}
//Spawns Enemy
function addBaddie(evt:TimerEvent):void
{
updateScore(25);
var baddie:Baddie = new Baddie();
var side:Number = Math.ceil(Math.random() * 4);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = - baddie.height;
}
else if (side == 2)
{
baddie.x = stage.stageWidth + baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
else if (side == 3)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y = stage.stageHeight + baddie.height;
}
else if (side == 4)
{
baddie.x = - baddie.width;
baddie.y = Math.random() * stage.stageHeight;
}
baddie.speed = baddieSpeed;
addChild(baddie);
baddies.push(baddie);
baddieCounter += 1;
if (baddieCounter == levelKR)
{
timer.stop();
}
}
//Moves Enemy
function moveBaddies():void
{
for (var i:int = 0; i < baddies.length; i++)
{
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
if (baddies[i].hitTestPoint(rbDash.x,rbDash.y,true))
{
removeChild(baddies[i]);
baddies.splice(i, 1);
//HealthBar.gotoAndStop(HealthBar.currentFrame + baddieDamage);
killCounter += 1;
checkKillCounter();
//if (HealthBar.currentFrame == 100)
{
gotoAndStop(5);
}
}
else
{
checkForHit(baddies[i]);
}
}
}
//Hit detection
function checkForHit(baddie:Baddie):void {//Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
for (var i:int = 0; i < bullets.length; i++)
{
if (baddie.hitTestPoint(bullets[i].x,bullets[i].y,true))
{
removeChild(baddie);
removeChild(bullets[i]);
baddies.splice(baddie.indexOf(baddie), 1);
bullets.splice(bullets[i]);
updateScore(100);
killCounter += 1;
checkKillCounter();
}
}
}
//Updates score
function updateScore(points:int):void
{
score += points;
Score.text = String("Points: "+score);
}
//stops timers
function timerStop():void
{
timer.stop();
energyTimer.stop();
healthTimer.stop();
}
//Y axis movement
//totaly not a code snippet
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
rbDash.y -= 5;
}
if (downPressed)
{
rbDash.y += 5;
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = true;
break;
};
case Keyboard.DOWN :
{
downPressed = true;
break;
}
}
};
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP :
{
upPressed = false;
break;
};
case Keyboard.DOWN :
{
downPressed = false;
break;
}
}
};
//makes the deg2rad work for the bullets/enemy
function deg2rad(degree)
{
return degree * (Math.PI / 180);//Had issues with "deg2rad" functions
}
//Removes listeners
function removeAllListeners():void
{
stage.removeEventListener(MouseEvent.MOUSE_DOWN, fireGun);
stage.removeEventListener(Event.ENTER_FRAME, moveObjects);
timer.removeEventListener(TimerEvent.TIMER, addBaddie);
}
//Checks if level end
function checkKillCounter():void
{
EnemiesLeft.text = ("Enemies Left: "+String(levelKR - killCounter));
if (killCounter == levelKR)
{
shutdown();
gotoAndStop(3);
}
}
//Stops everything
function shutdown():void
{
timerStop();
removeAllListeners();
removeChild(target);
}
I get Level 1, Layer 'Actions', Frame 1, Line 166 1046: Type was not found or was not a compile-time constant: Baddie.
Thanks Guys
Im trying to get this done today so i can move on
Is Baddie a class that is in the default package? If not, you need to import it:
import packagename.Baddie;
If Baddie is a library symbol, make sure you've checked 'Export for ActionScript' and that the linkage name is correct. Also make sure that is is exported in frame 1, or at least before or on the frame that your code is on.
In you Library, right click on Baddie and choose "properties" and check "export for ActionScript". Now you can use Baddie as a class that extends MovieClip.
Sorry, I didn't notice this was already recommended. Basically, your error cannot find a Class named Baddie, hence why you need to specify the custom class through the Library instance.

TypeError: Error #1009: Cannot access a property or method of a null reference

I am creating a platformer game. However, I have encountered an error after creating a collision boundary on platform to make the player jump on the platform without dropping.
I have create a rectangle box and I export it as platForm
Here's the output of the error:
The error keep repeating itself over and over again....
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Boy/BoyMove()
Main class:
package
{
import flash.display.*;
import flash.text.*;
import flash.events.*;
import flash.utils.Timer;
import flash.text.*;
public class experimentingMain extends MovieClip
{
var count:Number = 0;
var myTimer:Timer = new Timer(10,count);
var classBoy:Boy;
//var activateGravity:gravity = new gravity();
var leftKey, rightKey, spaceKey, stopAnimation:Boolean;
public function experimentingMain()
{
myTimer.addEventListener(TimerEvent.TIMER, scoreUp);
myTimer.start();
classBoy = new Boy();
addChild(classBoy);
stage.addEventListener(KeyboardEvent.KEY_DOWN, pressTheDamnKey);
stage.addEventListener(KeyboardEvent.KEY_UP, liftTheDamnKey);
}
public function pressTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = true;
stopAnimation = false;
}
if (event.keyCode == 39)
{
rightKey = true;
stopAnimation = false;
}
if (event.keyCode == 32)
{
spaceKey = true;
stopAnimation = true;
}
}
public function liftTheDamnKey(event:KeyboardEvent):void
{
if (event.keyCode == 37)
{
leftKey = false;
stopAnimation = true;
}
if (event.keyCode == 39)
{
rightKey = false;
stopAnimation = true;
}
if (event.keyCode == 32)
{
spaceKey = false;
stopAnimation = true;
}
}
public function scoreUp(event:TimerEvent):void
{
scoreSystem.text = String("Score : "+myTimer.currentCount);
}
}
}
Boy class:
package
{
import flash.display.*;
import flash.events.*;
public class Boy extends MovieClip
{
var leftKeyDown:Boolean = false;
var upKeyDown:Boolean = false;
var rightKeyDown:Boolean = false;
var downKeyDown:Boolean = false;
//the main character's speed
var mainSpeed:Number = 15;
//whether or not the main guy is jumping
//var mainJumping:Boolean = false;
var mainJumping:Boolean = false;
//how quickly should the jump start off
var jumpSpeedLimit:int = 40;
//the current speed of the jump;
var jumpSpeed:Number = 0;
var gravity:Number = 10;
var theGround:ground = new ground();
//var theCharacter:MovieClip;
public var currentX,currentY:int;
public function Boy()
{
this.x = 600;
this.y = 540;
addEventListener(Event.ENTER_FRAME, BoyMove);
}
public function BoyMove(event:Event):void
{
currentX = this.x;
currentY = this.y;
if (MovieClip(parent).leftKey)
{
currentX -= mainSpeed;
MovieClip(this).scaleX = 1;
}
if (MovieClip(parent).rightKey)
{
currentX += mainSpeed;
MovieClip(this).scaleX = -1;
}
if (MovieClip(parent).spaceKey || mainJumping)
{
mainJump();
}
this.x = currentX;
this.y = currentY;
}
public function mainJump():void
{
currentY = this.y;
if (! mainJumping)
{
mainJumping = true;
jumpSpeed = jumpSpeedLimit * -1;
currentY += jumpSpeed;
}
else
{
if (jumpSpeed < 0)
{
jumpSpeed *= 1 - jumpSpeedLimit / 250;
if (jumpSpeed > -jumpSpeedLimit/12)
{
jumpSpeed *= -2;
}
}
}
if (jumpSpeed > 0 && jumpSpeed <= jumpSpeedLimit)
{
jumpSpeed *= 1 + jumpSpeedLimit / 120;
}
currentY += jumpSpeed;
if (MovieClip(this).y > 500)
{
mainJumping = false;
MovieClip(this).y = 500;
}
this.y = currentY;
}
}
}
Platformer class: This is the class I want to set the boundary for the rectangle (platForm)
package
{
import flash.events.*;
import flash.display.MovieClip;
public class platForm extends MovieClip
{
var level:Array = new Array();
var classBoys:Boy = new Boy();
var speedx:int = MovieClip(classBoys).currentX;
public function platForm()
{
for (var i = 0; i < numChildren; i++)
{
if (getChildAt(i) is platForm)
{
level.push(getChildAt(i).getRect(this));
}
}
for (i = 0; i < level.length; i++)
{
if (MovieClip(classBoys).getRect(this).intersects(level[i]))
{
if (speedx > 0)
{
MovieClip(classBoys).x = level[i].left - MovieClip(classBoys).width/2;
}
if (speedx < 0)
{
MovieClip(classBoys).x = level[i].right - MovieClip(classBoys).width/2;
}
}
}
}
}
}
It's a little difficult to see exactly what is happening without being able to run your code, but the error is saying that something within your BoyMove() method is trying to reference a property (or method) of something that is null. Having looked at the BoyMove() method, I can see that there isn't a lot there that could cause this problem. The other two candidates would be
MovieClip(parent)
or
MovieClip(this)
You are attempting to access properties of both of those MovieClips. One of them must not be initialized as you expect. I suggest you do some basic debugging on that method by commenting out the lines with MovieClip(parent) and see if you still get the error. Then try the same with the line with MovieClip(this). That should be able enough to isolate the issue.

Netstream audio playing twice

I am new to flash (this is the first time I've ever used it or actionscript) and I'm trying to make a video player. The video player gets params from the embed code and pulls the videos from a folder on the server.
I've got the following code (I've removed everything that I'm 100% sure isn't causing my problem):
import flash.net.NetConnection;
import flash.net.NetStream;
import flash.media.Video;
import flash.events.NetStatusEvent;
import flash.events.MouseEvent;
import flash.events.FullScreenEvent;
import flash.events.Event;
import flash.ui.Mouse;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.TextFormat;
import flash.media.SoundTransform;
var nc:NetConnection;
var ns:NetStream;
var ns2:NetStream;
var video:Video;
var video2:Video;
//get filename parameters from embed code
var filename:String = root.loaderInfo.parameters.filename;
var filename2:String = root.loaderInfo.parameters.filename2;
var t:Timer = new Timer(5000);
var duration;
var currentPosition:Number;
var st:Number;
var started:Boolean;
Object(this).mcPlay.buttonMode = true;
Object(this).mcPause.buttonMode = true;
Object(this).ScreenClick.buttonMode = true;
Object(this).mcMax.buttonMode = true;
Object(this).mcSwitcher.buttonMode = true;
Object(this).mcPause.addEventListener(MouseEvent.CLICK,PlayPause);
Object(this).mcPlay.addEventListener(MouseEvent.CLICK,PlayPause);
Object(this).ScreenClick.addEventListener(MouseEvent.CLICK,PlayPause);
Object(this).mcMax.addEventListener(MouseEvent.CLICK,Maximize);
Object(this).slideVolume.addEventListener(Event.CHANGE, ChangeVolume);
Object(this).mcSwitcher.addEventListener(MouseEvent.CLICK, ToggleSwitcher);
t.addEventListener(TimerEvent.TIMER, TimerComplete);
stage.addEventListener(MouseEvent.MOUSE_MOVE, resetTimer);
stage.addEventListener(MouseEvent.MOUSE_DOWN, resetTimer);
stage.addEventListener(MouseEvent.MOUSE_UP, resetTimer);
stage.addEventListener(Event.ENTER_FRAME, videoTimer);
if (!nc) start();
var IsPaused:String;
function start():void
{
Object(this).slideVolume.maximum = 100;
Object(this).slideVolume.value = 100;
started = false;
var tf:TextFormat = new TextFormat();
tf.color = 0xFFFFFF;
tf.bold = true;
this.lblTime.setStyle("textFormat", tf);
connect();
t.start();
}
function connect():void
{
nc = new NetConnection();
nc.client = this;
nc.addEventListener(NetStatusEvent.NET_STATUS, OnNetStatus);
nc.connect(null);
}
function OnNetStatus(e:NetStatusEvent):void
{
switch(e.info.code)
{
case "NetConnection.Connect.Success":
if (!started)
{
started = true;
stream();
}
else
{
finish();
}
break;
default:
finish();
break;
}
}
function stream():void
{
ns = new NetStream(nc);
ns.client = this;
ns.bufferTime = 5; // set the buffer time to 5 seconds
if ((filename2 != null) && (filename2.length > 0))
{
ns2 = new NetStream(nc)
//ns2.client = this; //Uncomment to use ns2 vid for duration info
ns2.bufferTime = 5; // set the buffer time to 5 seconds
startVideo(2);
currentPosition = 1; //Default
ns.seek(0);
ns2.seek(0);
}
else
{
this.mcSwitcher.visible = false;
startVideo(1);
ns.seek(0);
}
}
function startVideo(num:Number):void
{
var startVolume:SoundTransform = new SoundTransform();
startVolume.volume = slideVolume.value / 100;
if (num == 2)
{
video = new Video(320,180);
video.x = 0;
video.y = 90;
addChild(video);
video.attachNetStream(ns);
ns.checkPolicyFile = false;
ns.play(filename); //path/filename
setChildIndex(video,1);
video2 = new Video(320,180);
video2.x = 320;
video2.y = 90;
addChild(video2);
video2.attachNetStream(ns2);
ns2.checkPolicyFile = false;
ns2.play(filename2); //path/filename
setChildIndex(video2,1);
ns.soundTransform = startVolume;
var videoVolumeTransform2:SoundTransform = new SoundTransform();
videoVolumeTransform2.volume = 0;
ns2.soundTransform = videoVolumeTransform2;
ns2.receiveAudio(false);
}
else if (num == 1)
{
video = new Video(640,360);
video.x = 0;
video.y = 0;
addChild(video);
video.attachNetStream(ns);
ns.checkPolicyFile = false;
ns.play(filename); //path/filename
setChildIndex(video,1);
ns.soundTransform = startVolume;
}
IsPaused = "playing";
this.removeChild(mcPlay);
setChildIndex(this.ScreenClick,0);
setChildIndex(this.mcTitleOverlay,2);
}
function ShowControls ():void
{
for (var i:int = 0; i < Object(root).numChildren; i++)
{
switch (Object(root).getChildAt(i))
{
case mcPause:
if (IsPaused != "paused")
Object(root).getChildAt(i).visible = true;
break;
case mcPlay:
if (IsPaused != "playing")
Object(root).getChildAt(i).visible = true;
break;
case mcSwitcher:
if ((filename2 != null) && (filename2.length > 0))
Object(root).getChildAt(i).visible = true;
break;
default:
Object(root).getChildAt(i).visible = true; //Bring back everything else
break;
}
ScreenClick.y = 154;
}
}
function videoTimer(e:Event):void
{
var curTime = ns.time; //Current time in seconds
var curMinutes = Math.floor(curTime / 60); //Get the minutes
var curSeconds = Math.floor(curTime % 60); //Get the leftover seconds
var durMinutes = Math.floor(duration / 60);
var durSeconds = Math.floor(duration % 60);
//Add the zeroes to the begining of the seconds if it is needed.
if (curSeconds < 10)
curSeconds = "0" + curSeconds;
if (durSeconds < 10)
durSeconds = "0" + durSeconds;
Object(this).lblTime.text = curMinutes + ":" + curSeconds + " / " + durMinutes + ":" + durSeconds;
}
function PlayPause (e:MouseEvent):void
{
switch (IsPaused)
{
case "playing":
IsPaused = "paused";
this.mcPlay.visible = true;
this.mcPause.visible = false;
ns.togglePause();
ns2.togglePause();
break;
case "paused":
IsPaused = "playing";
this.mcPause.visible = true;
this.mcPlay.visible = false;
ns.togglePause();
ns2.togglePause();
break;
default:
//
break;
}
}
The problem I have is small but frustrating (I've spend most of today trying to figure it out with zero progress made). It is thus: Everything works perfectly, except that when the videos load up and play, sound plays twice (for the video that has sound enabled). I am at my wits end trying to figure this out, any help would be greatly appreciated!
Thanks!
EDIT:
Ok, on further research (re-writing every function very simply and seeing if the problem goes away with the features) I've determined that the following function is the root of all evil (or at least my problems):
function startVideo(num:Number):void
{
var startVolume:SoundTransform = new SoundTransform();
startVolume.volume = Object(this).slideVolume.sldVol.value / 100;
if (num == 2)
{
video = new Video(320,180);
video.x = 0;
video.y = 90;
addChild(video);
video.attachNetStream(ns);
ns.checkPolicyFile = false;
ns.play(filename); //path/filename
this.removeChild(btnPlay);
setChildIndex(video,1);
video2 = new Video(320,180);
video2.x = 320;
video2.y = 90;
addChild(video2);
video2.attachNetStream(ns2);
ns2.checkPolicyFile = false;
ns2.play("test.mp4"); //path/filename
setChildIndex(video2,1);
ns.soundTransform = startVolume;
var videoVolumeTransform2:SoundTransform = new SoundTransform();
videoVolumeTransform2.volume = 0;
ns2.soundTransform = videoVolumeTransform2;
ns2.receiveAudio(false);
}
else if (num == 1)
{
video = new Video(640,360);
video.x = 0;
video.y = 0;
addChild(video);
video.attachNetStream(ns);
ns.checkPolicyFile = false;
ns.play("test.flv"); //path/filename
setChildIndex(video,1);
ns.soundTransform = startVolume;
}
IsPaused = "playing";
this.removeChild(btnPlay);
setChildIndex(this.ScreenClick,0);
//setChildIndex(this.mcTitleOverlay,2);
}
I shall persevere with my troubleshooting (I've isolated the problem, hopefully the next step is a solution!

gotoandstop problems actionscript 3

I have a memory game program and when the timer runs out, I want it to go to frame 3 where it displays the "game failed" page.
I have it all set up, except when the game runs out of time, the frame just appears to overlap the original frame, instead of going to a completely separate page.
Can anyone help me?
Here is my code:
package {
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.display.MovieClip;
import flash.text.TextField;
public class MemoryGame extends MovieClip{
private var firstTile:cards;
private var secondTile:cards;
private var pauseTimer:Timer;
private var score:int;
private var cardCount:int;
var seconds:Number;
var minutes:Number;
var numberDeck:Array = new Array(1,1,2,2,3,3,4,4,5,5,6,6);
public function MemoryGame(){
//TIMER FUNCTION
var levelTimer:Timer = new Timer(1000, 180);
levelTimer.addEventListener(TimerEvent.TIMER_COMPLETE, timerCompleteHandler);
levelTimer.addEventListener(TimerEvent.TIMER, timerHandler);
// LEVEL FUNCTION
easyBtn.addEventListener(MouseEvent.CLICK, easyButtonClicked);
medBtn.addEventListener(MouseEvent.CLICK, medButtonClicked);
hardBtn.addEventListener(MouseEvent.CLICK, hardButtonClicked);
score = 0;
txtScore.text=""+score;
//Level button events
function easyButtonClicked(e:MouseEvent):void{
removeChild(levelText);
trace("easy button clicked!");
seconds = 0;
minutes = 1;
txtTime.text = "1:00";
levelTimer.start();
setupTiles();
}
function medButtonClicked(e:MouseEvent):void{
removeChild(levelText);
trace("medium button clicked!");
seconds = 30;
minutes = 0;
txtTime.text = "0:30";
levelTimer.start();
setupTiles();
}
function hardButtonClicked(e:MouseEvent):void{
removeChild(levelText);
trace("hard button clicked!");
seconds = 15;
minutes = 0;
txtTime.text = "0:15";
levelTimer.start();
setupTiles();
}
//Timer handlers
function timerHandler(e:TimerEvent):void {
if (seconds > 00) {
seconds -=1;
}
else {
if (minutes > 0) {minutes -=1;seconds = 59;}
}
txtTime.text = minutes+":"+(seconds >= 10 ? seconds : "0"+seconds);
}
function timerCompleteHandler(e:TimerEvent):void {
e.target.reset();
e.target.stop();
trace("game over!");
}
//Tiles set up
function setupTiles(){
for(x=1; x<=4; x++) {
for (y=1; y<=3; y++){
var randomCard = Math.floor(Math.random()*numberDeck.length);
var tile:cards = new cards();
tile.card = numberDeck[randomCard];
numberDeck.splice(randomCard,1);
tile.gotoAndStop(9);
tile.x = (x-1) * 150;
tile.y = (y-1) * 200;
tile.addEventListener(MouseEvent.CLICK,tileClicked);
addChild(tile);
cardCount = cardCount + 1
}
}
}
}
public function tileClicked(event:MouseEvent) {
var clicked:cards = (event.currentTarget as cards);
if (firstTile == null){
firstTile = clicked;
firstTile.gotoAndStop(clicked.card);
}
else if (secondTile == null && firstTile != clicked){
secondTile = clicked;
secondTile.gotoAndStop(clicked.card);
if (firstTile.card == secondTile.card){
pauseTimer = new Timer(1000, 1);
pauseTimer.addEventListener(TimerEvent.TIMER_COMPLETE,removeCards);
pauseTimer.start();
}
else {
pauseTimer = new Timer(1000, 1);
pauseTimer.addEventListener(TimerEvent.TIMER_COMPLETE,resetCards);
pauseTimer.start();
}
}
if (seconds == 0){
this.gotoAndStop(2);
pauseTimer.stop();
//levelTimer.stop();
}
}
public function resetCards(event:TimerEvent) {
firstTile.gotoAndStop(9);
secondTile.gotoAndStop(9);
firstTile = null;
secondTile = null;
pauseTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,resetCards);
score = score - 2;
txtScore.text=""+score;
}
public function removeCards(event:TimerEvent){
removeChild(firstTile);
removeChild(secondTile);
firstTile = null;
secondTile = null;
pauseTimer.removeEventListener(TimerEvent.TIMER_COMPLETE,removeCards);
score = score + 10;
txtScore.text=""+score;
cardCount = cardCount - 2;
trace("Cardcount: " + cardCount);
if (cardCount == 0){
this.gotoAndStop(2);
txtFinalScore.text=" "+score;
pauseTimer.stop();
}
}
}
}
Thank you so much!
When you add an object using addChild(object) it isn't associated with keyframes along the timeline.
So what you need to do is rather than jumping to frame 2, removeChild(object) or object.visible = false all children you don't want and addChild(object) your 'out of time' assets.
A good work ethic is to create destroy() functions that remove and null any unwanted assets. This way you can easily remove unwanted items and free up memory.