How to display or move sprite in as3 side scroller? - actionscript-3

I have a sprite in my library called myRocket but it won't show up.
I made my sprite a movie clip then I deleted it off the actual page so it was just in the library. I thought using this code, the sprite would appear once I started up the game but it does not.
import flash.display.MovieClip;
stop() ;
removeChild(myButton);
var myReturn:Return=new Return();
addChild(myReturn);
myReturn.x=390;
myReturn.y=10;
myReturn.addEventListener(MouseEvent.CLICK, return1Function);
var up:Boolean;
var down:Boolean;
var left:Boolean;
var right:Boolean;
var speed:int;
function return1Function(evt:MouseEvent):void{
gotoAndStop("menu");
}
var myRocket:MovieClip;
addChild(myRocket);
myRocket.x=200;
myRocket.y=150;
function KeyboardDemo() {
myRocket.x = 200;
myRocket.y = 100;
addChild(myRocket);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);
}
function keyPressedDown(event:KeyboardEvent):void {
var key:uint = event.keyCode;
var step:uint = 5
switch (key) {
case Keyboard.LEFT :
myRocket.x -= step;
break;
case Keyboard.RIGHT :
myRocket.x += step;
break;
case Keyboard.UP :
myRocket.y -= step;
break;
case Keyboard.DOWN :
myRocket.y += step;
break;
}
}

You need to initialize your object before you place it to the stage. You have only declared a variable at the line "var myRocket:MovieClip;" instead it should at least (not sure about whatever logic you have there" read like above with "Return" whatever it was: var myRocket:MovieClip=new Rocket(); Here "Rocket" is the library name of the sprite.

Related

AS3: Why is a line created with .graphics appearing in two different places and when removed with parent.visible = false, only one goes?

Nobody seems to have this question already so I asked it because I've spent a few hours trying to debug this and can't find a solution;
Essentially, I have a function called draw, which is declared in my document class:
public function draw(Target: MovieClip,mX: int,mY: int,lX: int,lY: int):void {
Target.graphics.clear();
Target.graphics.lineStyle(1,0x000000,1);
Target.graphics.moveTo(mX,mY);
Target.graphics.lineTo(lX,lY);
}
I call it later to draw two lines, on two different MovieClips:
draw(Line,Line.mX,Line.mY,Mirror.x + (Mirror.width / 2),Line.lY);
draw(nextLine,(Mirror.x + (Mirror.width / 2)),200,(Mirror.x + (Mirror.width / 2)),0);
where
var Line: MovieClip = new MovieClip();
var Mirror: MovieClip = new mirror();
and Mirror is draggable, so Mirror.x changes whenever it is dragged.
Line is a line made using .graphics and Line.mX is equal to the Line.graphics.moveTo X value last time it was modified. Line.mY is the same, but for the Y coordinate. I set these values by doing this:
Line.mX = 0;
Line.mY = 200;
Line.lX = 550;
Line.lY = 200;
But with whatever values I want to draw the line, with lX and lY being equal to the X and Y coordinates of Line.graphics.lineTo. Then I draw Line using my draw function like this:
draw(Line,Line.mX,Line.mY,Line.lX,Line.lY);
Then it gets more complex because, actually, Line is just one line in an array of lines, created like this:
public var lines = [line0,line1,line2,line3,line4,line5,line6,line7,line8];
and each of those lines is created like this (with 0 being replaced by the line's number, respectively):
public var line0: MovieClip = new MovieClip();
then I give each line a number and a name, add them to the stage and hide them like this:
for each(var setupLine:MovieClip in lines) {
setupLine.num = (lines.indexOf(setupLine));
setupLine.name = ('line' + setupLine.num);
addChild(setupLine);
setupLine.visible = false;
}
Then, after making line0 visible, because I need to see it at the start, I loop through each line in a function that runs on ENTER_FRAME, and set the value of nextLine to a different value each time I run the loop like this:
for each(var Line:MovieClip in lines) {
nextLine = this['line' + (Line.num + 1)];
}
Within that loop, I then loop through a few other arrays, then check for a collision with the selected Line and another selected MovieClip from another array, which I wont go into or this question will be longer than the code for node.js.
So essentially, if the collision with the two MovieClips is present, I draw the line that I mentioned at the top of my question. But for some reason, although Line draws correctly, nextLine draws correctly, but a duplicate of it is drawn across the Y axis at 0, and stops where nextLine is on the Y axis (nextLine is vertical, so it has the same Y value at the start as at the end).
Even stranger, when I try to hide nextLine if the collision with the two MovieClips is no longer present, using this code:
nextLine.visible = false;
it only hides the version of nextLine that runs along the top of the stage, which I didn't even intend to create in the start.
EDIT
here is a link to the current source code
Here is a link to the entire project files with the original source code
copy/paste the new source code from the pastebin link to get the new version
Thanks in advance,
-Raph
I figured out how to do this, code is
package {
import flash.events.*;
import flash.utils.*;
import flash.display.*;
[SWF(backgroundColor="0xbdc3c7")]
public class LightStage extends MovieClip {
//import classes
public var globeClass:Globe = new Globe();
public var mirrorClass:Mirror = new Mirror();
public var lineClass:Line = new Line();
//create all stage objects
public var curLine:Line
public var nextLine:Line;
public var curMirror:Mirror;
//create containers
public var mirrors:Vector.<Mirror> = new Vector.<Mirror>(); //a vector is an array, but every member has to be (or subclass) the specified class
public var globes:Vector.<Globe> = new Vector.<Globe>();
public var lines:Vector.<Line> = new Vector.<Line>();
trace('lightstage: working');
//create level object
public var curLevel:int = -1;
//create dependent variables
public var kill: Boolean = true;
//init function
public function LightStage() {
//setup MovieClips
var i:int = 0;
for (i = 0; i < 4; i++) {
mirrors.push(new Mirror());
}
for (i = 0; i < 4;i++ ) {
globes.push(new Globe());
}
var tmpLine:Line;
for (i = 0; i < 10; i++) {
tmpLine = new Line();
lines.push(tmpLine);
addChild(tmpLine);
tmpLine.visible = false;
}
//create ENTER_FRAME listener
stage.addEventListener(Event.ENTER_FRAME,enterFrame);
//start the game
levelUp();
}
//levelUp function
public function levelUp() {
curLevel++;
curLine = lines[curLevel]; //set line to the current level
curLine.curX = 0;
curLine.curY = 200;
curLine.draw(550, 200);
curLine.visible = true;
//show and position mirrors and globes
curMirror = mirrors[curLevel];
addChild(curMirror);
curMirror.x = 250;
curMirror.y = 350;
var curGlobe:Globe = globes[curLevel];
addChild(curGlobe);
curGlobe.x = 100;
curGlobe.y = 50;
//set mirror types
curMirror.gotoAndStop(2);
trace("you are now on level " + (curLevel + 1) + "!");
}
//ENTER_FRAME function
public function enterFrame(event:Event) {
//line1.visible = true;
for (var i:int = 0; i < lines.length;i++){
if (i < lines.length - 1) nextLine = lines[i + 1]; //check for out of bounds before assignment next line
if (lines[i].visible == true) {
kill = true;
for each(var mirror:Mirror in mirrors) {
if (lines[i].visible && mirror.stage && mirror.hitTestObject(lines[i])) { //for efficiency, do the hit test last in the if statement
for each(var globe:Globe in globes) {
//Looped through Mirrors and Lines and checked for collision - if collision is present, we loop through globes here
if (nextLine && nextLine.stage) {
addChild(nextLine);
}
//check for active globes
if (lines[i].visible && lines[i].hitTestObject(globe)) {
//check if the selected line touches the selected globe - if it does then we will start the timer for that globe
if (!globe.running){
globe.start();
//trace('timing');
kill = false;
}
}
else {
globe.reset();
}
switch(mirror.currentFrame) {
case 1:
break;
case 2:
//trace('live a life you will remember' + Math.random());
if(nextLine) nextLine.visible = true;
lines[i].draw(mirror.x + (mirror.width / 2),lines[i].curY);
if (nextLine) {
nextLine.curX = mirror.x + (mirror.width / 2);
nextLine.curY = 200;
nextLine.draw(mirror.x + (mirror.width / 2), 0);
}
kill = false;
break;
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
trace(mirror.currentFrame);
kill = false;
break;
}
}
}
else if (lines[i].visible && mirror.stage && lines[i].stage){
if (kill && nextLine){
nextLine.graphics.clear();
nextLine.visible = false;
}
}
}
}
}
}
}
}
//MIRROR CLASS DECLARATION
import flash.events.MouseEvent;
class Mirror extends MovieClip {
trace('mirror: working');
public function Mirror() {
this.addEventListener(MouseEvent.MOUSE_DOWN,onDown,false,0,true);
}
private function onDown(e:MouseEvent):void {
//add the mouse up listener on the stage, that way it's consistent even if the user drags so fast that the mouse leaves the bounds of the mirror
stage.addEventListener(MouseEvent.MOUSE_UP, onUp, false, 0, true);
this.startDrag();
}
private function onUp(e:MouseEvent):void {
//we need to remove the listener from the stage now
stage.removeEventListener(MouseEvent.MOUSE_UP, onUp, false);
this.stopDrag();
}
}
//LINE CLASS DECLARATION
import flash.display.Graphics;
class Line extends MovieClip {
trace('line: working');
public var curX:int;
public var curY:int;
public function Line():void {
}
public function draw(toX:int,toY:int):void {
graphics.clear();
graphics.lineStyle(1,0x000000,1);
graphics.moveTo(curX,curY);
graphics.lineTo(toX, toY);
curX = toX;
curY = toY;
}
}
//GLOBE CLASS DECLARATION
import flash.display.MovieClip;
import flash.events.TimerEvent;
import flash.utils.Timer;
class Globe extends MovieClip {
trace('globe: working');
private var timer:Timer = new Timer(3 * 100, 5);
public function Globe():void {
timer = new Timer(300, 5);
timer.addEventListener(TimerEvent.TIMER, repeatShine, false, 0, true);
}
public function reset():void {
timer.reset();
}
public function start():void {
timer.start();
}
public function get running():Boolean { return timer.running; };
private function repeatShine(e:TimerEvent):void {
}
}

as3 navigation - gotoAndPlay script not working consistently

I think I've made an error in logic somewhere but can't find it, I have a movie clip which contains 4 further animated movieclips, each with stop() actions at specific frames, and 2 buttons, 1 to move left and another to move right, the animations work as expected if the user clicks say right, right, right, right, left, left, left, left for the first time, but then things stop evaluating properly.
Am using switch case statements on a variable to pick out the mc to animate, would I be better of using an If Else statement? Heres my code, as may be obvious actionscript is not my forte!
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.events.Event;
import fl.text.TLFTextField;
import fl.transitions.Tween;
import fl.transitions.easing.*;
import fl.transitions.TweenEvent;
// Global variables
var mcWidth:int = 768;
var mcPosInc:int = 0;
var boxAnimPlay:int = 1;
var mcMoving:Boolean = false;
var buttonClicked:String = "right";
var mcLeft;
var mcRight;
addEventListener(Event.ENTER_FRAME, frameHandler);
// frame Handler
function frameHandler(event:Event):void
{
// Initialize button click events
controlGrp.bttn_left.addEventListener(MouseEvent.CLICK, goLeft);
controlGrp.bttn_right.addEventListener(MouseEvent.CLICK, goRight);
function goLeft(e:MouseEvent):void {
buttonClicked = "left";
// change position
if (mcPosInc > 0 && mcMoving == false) {
mcMoving = true;
mcPosInc --;
boxAnimPlay --;
// Scroll mc1
mcLeft = new Tween(mc1, "x", Regular.easeOut, mc1.x, mc1.x + mcWidth, 1.5, true);
mcLeft.addEventListener(TweenEvent.MOTION_FINISH, end);
function end(event:TweenEvent) {
mcMoving = false;
}
if (boxAnimPlay >= 1) {
switch (boxAnimPlay) {
case 3:
mc1.box4.gotoAndPlay(17);
mc1.box3.gotoAndPlay(31);
break;
case 2:
mc1.box2.gotoAndPlay(31);
mc1.box3.gotoAndPlay(46);
break;
case 1:
mc1.box1.gotoAndPlay(17);
mc1.box2.gotoAndPlay(46);
break;
}
}
trace(boxAnimPlay);
trace(buttonClicked);
}
}
}
// Play movie tests
function goRight(e:MouseEvent):void {
buttonClicked = "right";
// change position
if (mcPosInc < 3 && mcMoving == false) {
mcMoving = true;
mcPosInc ++;
boxAnimPlay ++;
// Scroll mc1
mcRight = new Tween(mc1, "x", Regular.easeOut, mc1.x, mc1.x - mcWidth, 1.5, true);
mcRight.addEventListener(TweenEvent.MOTION_FINISH, end);
function end(event:TweenEvent) {
mcMoving = false;
}
if (boxAnimPlay <= 4) {
switch (boxAnimPlay) {
case 1:
break;
case 2:
mc1.box1.gotoAndPlay(1);
mc1.box2.gotoAndPlay(1);
break;
case 3:
mc1.box2.gotoAndPlay(16);
mc1.box3.gotoAndPlay(1);
break;
case 4:
mc1.box3.gotoAndPlay(16);
mc1.box4.gotoAndPlay(1);
break;
}
}
trace(boxAnimPlay);
trace(buttonClicked);
}
// Add Text Labels to TitleGroup
switch (boxAnimPlay) {
case 1:
readout.text = "test";
break;
}
}
I fixed it, basically the frames I was targeting in the gotoAndPlay contained stop() statements, once I targeted the subsequent frames, ie
Instead of:
switch (boxAnimPlay) {
case 3:
mc1.box4.gotoAndPlay(17);
mc1.box3.gotoAndPlay(31);
break;
case 2:
mc1.box2.gotoAndPlay(31);
mc1.box3.gotoAndPlay(46);
break;
case 1:
mc1.box1.gotoAndPlay(17);
mc1.box2.gotoAndPlay(46);
break;
}
I used this:
switch (boxAnimPlay) {
case 3:
mc1.box4.gotoAndPlay(17);
mc1.box3.gotoAndPlay(32); // no stop on subsequent frame
break;
case 2:
mc1.box2.gotoAndPlay(32); // no stop on subsequent frame
mc1.box3.gotoAndPlay(47); // no stop on subsequent frame
break;
case 1:
mc1.box1.gotoAndPlay(17);
mc1.box2.gotoAndPlay(47); // no stop on subsequent frame
break;
}

AS3 not recognising MovieClips - 1046: Type was not found or was not a compile-time constant: MP_00

So Im new to AS3, trying to make a simple videogame for smartphones.
And it was all going smooth until I hit this problem.
I was using and manipulating objects from timeline without a problem and than all the sudden whatever I try I get the 1046.
Here is some code that gets an error:
mp = new MP_00();
And at the top I have this:
import flash.display.MovieClip;
var mp:Movieclip;
And at the end this:
function mapMove(){
mp.y = mp.y - playerSpeed;
}
Im searching for a solution all the time, but nobody seems to have the same problem.
I do have AS linkage set to MP_00 and witch ever object I try to put in, it dosent work.
While objects put in on the same way before, they work.
For example I have this
var player:MovieClip;
player = new Player();
with AS Linkage set to Player, and that works.
This is all done in Flash Professional cs6
EDIT 1
full code
Keep in mind that a lot of stuff is placeholder or just not finished code.
On this code Im getting the error twice for the same object
Scene 1 1046: Type was not found or was not a compile-time constant:
MP_00.
Scene 1, Layer 'Actions', Frame 1, Line 165 1046: Type was not
found or was not a compile-time constant: MP_00.
Thats the errors.
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.text.engine.SpaceJustifier;
import flashx.textLayout.operations.MoveChildrenOperation;
/*----------------------------Main VARs-----------------------------*/
var STATE_START:String="STATE_START";
var STATE_START_PLAYER:String="STATE_START_PLAYER";
var STATE_PLAY:String="STATE_PLAY";
var STATE_END:String="STATE_END";
var gameState:String;
var player:MovieClip;
var playerSpeed:Number;
var map:Array;
var bullets:Array;
//holds civil vehicles
var civil:Array;
//holds enemy vehicles
var enemy:Array;
var explosions:Array;
var BBullet:MovieClip;
//maps
var mp:MovieClip;
/*
var MP_01:MovieClip;
var MP_02:MovieClip;
var MP_03:MovieClip;
*/
//sets the bullet type and properties
var BType = "BBasic";
var BProp:Array;
//bullet preperties by type
var BBasic:Array = new Array(1, 1, 100, 50, 0, new BBasicA());
/**
ARRAY SETTING
0 = bullet position (middle , back, sides etc...)
1-middle front
2-left side front
3-right side front
4-left and right side middle
5-back
7-left and right side wheels
1 = bullet direction
1-forward
2-back
3-sides
2 = fire speed (in millisecounds so 1000 = 1sec)
3 = speed of movement
4 = damage 10-100
5 = name of the firing animation in library
6 = name of launch animation in library
7 = name of impact animation in library
**/
var level:Number;
//BCivil speed and randomness
var BCSpeed:Number = 3;
var BCRand:Number = 120;
/*------------------------------Setup-------------------------------*/
introScreen.visible = false;
loadingScreen.visible = false;
gameScreen.visible = false;
endScreen.visible = false;
//map visibility
//MpRSimple.visible = false;
/*---------------------------Intro screen--------------------------*/
/*-----------------------------mainScreen---------------------------*/
mainScreen.play_btn.addEventListener(MouseEvent.CLICK, clickAway);
function clickAway(event:MouseEvent):void
{
gameStart();
}
function gameStart():void
{
//Move main screen from stage
mainScreen.visible = false;
//Begin loading the game
loadingScreen.visible = true;
gameState = STATE_START;
trace (gameState);
addEventListener(Event.ENTER_FRAME, gameLoop);
}
/*----------------------------gameLoop-----------------------------*/
function gameLoop(e:Event):void
{
switch(gameState)
{
case STATE_START:
startGame();
break;
case STATE_START_PLAYER:
startPlayer();
break;
case STATE_PLAY:
playGame();
break;
case STATE_END:
endGame();
break;
}
}
/*-_________________________-Game STATES-_________________________-*/
/*---------------------------STATE_START---------------------------*/
function startGame():void
{
level = 1; //setting level for enemies
//Graphics
//player icon
player = new Player();
//add bullet holder
bullets = new Array();
//basicCivil icon
civil = new Array();
//basicEnemy icon
enemy = new Array();
//holds explosions
explosions = new Array();
//map
//mp = new MP_00();
//var mp:MP_00 = new MP_00();
//Load map parts
//End startGame
gameState = STATE_START_PLAYER;
trace(gameState);
}
/*------------------------STATE_START_PLAYER-----------------------*/
function startPlayer():void
{
//start the player
//set possition of player
player.y = stage.stageHeight - player.height;
addChild(player);
addEventListener(Event.ENTER_FRAME, movePlayer);
//changing screens
gameScreen.visible = true;
//start game
gameState = STATE_PLAY;
trace(gameState);
}
//player controll
function movePlayer(e:Event):void
{
//gameScreen.visible = true;
//mouse\touch recognition
player.x = stage.mouseX;
player.y = stage.mouseY;
//player does not move out of the stage
if (player.x < 0)
{
player.x = 0;
}
else if (player.x > (stage.stageWidth - player.width))
{
player.x = stage.stageWidth + player.width;
}
}
//setting bullet type
if (BType == "BBasic")
{
BProp = BBasic;
/*case BMissile;
BProp = BMissile;
break; */
}
//creating bullets
//gameScreen.fire_btn.addEventListener(MouseEvent.CLICK, fireHandler());
/*
function fireHandler():void
{
var bulletTimer:Timer = new Timer (500);
bulletTimer.addEventListener(TimerEvent.TIMER, timerListener);
bulletTimer.start();
trace("nja");
}
function timerListener(e:TimerEvent):void
{
//need and if statement to determine the bullet speed and travel depended on type of bullet
var tempBullet:MovieClip = /*BProp[5] new BBasicA();
//shoots bullets in the middle
tempBullet.x = player.x +(player.width/2);
tempBullet.y = player.y;
//shooting speed
tempBullet.speed = 10;
bullets.push(tempBullet);
addChild(tempBullet);
//bullets movement forward
for(var i=bullets.length-1; i>=0; i--)
{
tempBullet = bullets[i];
tempBullet.y -= tempBullet.speed;
}
}
*/
/*----------------------------STATE_PLAY---------------------------*/
function playGame():void
{
//gameplay
//speedUp();
mapMove();
//fire();
makeBCivil();
makeBEnemy();
moveBCivil();
moveBEnemy();
vhDrops();
testCollision();
testForEnd();
removeExEplosions();
}
function mapMove(){
mp.y = mp.y - playerSpeed;
}
/*
function speedUp():void
{
var f:Number;
for (f<10; f++;)
{
var playerSpeed = playerSpeed + 1;
f = 0;
//mapMove();
MpRSimple = new MP_RS();
MpRSimple.y = MpRSimple.y - playerSpeed;
trace ("speed reset");
}
trace (f);
}
*/
function makeBCivil():void
{
//random chance
var chance:Number = Math.floor(Math.random()*BCRand);
if (chance <= 1 + level)
{
var tempBCivil:MovieClip;
//generate enemies
tempBCivil = new BCivil();
tempBCivil.speed = BCSpeed;
tempBCivil.x = Math.round(Math.random()*800);
addChild(tempBCivil);
civil.push(tempBCivil);
}
}
function moveBCivil():void
{
//move enemies
var tempBCivil:MovieClip;
for(var i:int = civil.length-1; i>=0; i--)
{
tempBCivil = civil[i];
tempBCivil.y += tempBCivil.speed
}
//testion colision with the player and screen out
if (tempBCivil.y > stage.stageHeight /* || tempBCivil.hitTestObject(player) */)
{
trace("ds hit");
//makeExplosion (player.x, player.y);
removeCivil(i);
//gameState = STATE_END;
}
}
//Test bullet colision
function testCollision():void
{
var tempBCivil:MovieClip;
var tempBEnemy:MovieClip;
var tempBullet:MovieClip;
//civil/bullet colision
civils:for(var i:int=civil.length-1; i>=0; i--)
{
tempBCivil = civil[i];
for (var j:int=bullets.length-1; j>=0; j--)
{
tempBullet = bullets[j];
if (tempBCivil.hitTestObject(tempBullet))
{
trace("laser hit the civil");
makeExplosion (tempBCivil.x, tempBCivil.y);
removeCivil(i);
removeBullet(j);
break civils;
}
}
}
//enemy/bullet colision
enemy:for(var k:int=enemy.length-1; k>=0; k--)
{
tempBEnemy = enemy[k];
for (var l:int=bullets.length-1; l>=0; l--)
{
tempBullet = bullets[l];
if (tempBEnemy.hitTestObject(tempBullet))
{
trace("bullet hit the Enemy");
makeExplosion (tempBEnemy.x, tempBEnemy.y);
removeEnemy(k);
removeBullet(l);
break enemy;
}
}
}
}
function makeExplosion(ex:Number, ey:Number):void
{
var tempExplosion:MovieClip;
tempExplosion = new boom();
tempExplosion.x = ex;
tempExplosion.y = ey;
addChild(tempExplosion)
explosions.push(tempExplosion);
}
function makeBEnemy():void
{
//random chance
var chance:Number = Math.floor(Math.random()*BCRand);
if (chance <= 1 + level)
{
var tempBEnemy:MovieClip;
//generate enemies
tempBEnemy = new BEnemy();
tempBEnemy.speed = BCSpeed;
tempBEnemy.x = Math.round(Math.random()*800);
addChild(tempBEnemy);
enemy.push(tempBEnemy);
}
}
function moveBEnemy():void
{
//move enemies
var tempBEnemy:MovieClip;
for(var i:int = enemy.length-1; i>=0; i--)
{
tempBEnemy = enemy[i];
tempBEnemy.y += tempBEnemy.speed
}
//testion colision with the player and screen out
if (tempBEnemy.y > stage.stageHeight /* || tempBCivil.hitTestObject(player) */)
{
trace("enemy");
//makeExplosion (player.x, player.y);
removeEnemy(i);
//gameState = STATE_END;
}
}
function vhDrops():void
{}
function testForEnd():void
{
//check damage
//end game
//gameState = STATE_END;
trace(gameState);
}
/*--------------------REMOVING BS FROM STAGE-----------------------*/
//removing civils
function removeCivil(idx:int):void
{
if(idx >= 0)
{
removeChild(civil[idx]);
civil.splice(idx, 1);
}
}
//removing enemies
function removeEnemy(idx:int):void
{
if(idx >= 0)
{
removeChild(enemy[idx]);
enemy.splice(idx, 1);
}
}
//removing civils
function removeBullet(idx:int):void
{
if(idx >= 0)
{
removeChild(bullets[idx]);
bullets.splice(idx, 1);
}
}
//removing expired explosions
function removeExEplosions():void
{
var tempExplosion:MovieClip;
for(var i=explosions.length-1; i>=0; i--)
{
tempExplosion = explosions[i];
if (tempExplosion.currentFrame >= tempExplosion.totalFrames)
{
removeExplosion(i);
}
}
}
//removing civils
function removeExplosion(idx:int):void
{
if(idx >= 0)
{
removeChild(explosions[idx]);
explosions.splice(idx, 1);
}
}
/*--------------------------STATE_END------------------------------*/
function endGame():void
{
}
/*gameScreen*/
/*endScreen*/
And Im sure theres some other bad code here but that doesent matter now.
Export for AS and AS Linkage is set:
http://i.stack.imgur.com/UvMAt.png
EDIT: removed the 2nd var declaration, still get the same error.
It would be great if you give more code and explanations, but here what I found about 1046 :
"One reason you will get this error is if you have an object on the stage with the same name as an object in your library."
Look at : http://curtismorley.com/2007/06/20/flash-cs3-flex-2-as3-error-1046/
Did you search any explanation on the Web for code 1046 ? Have you checked this one ?
I see that you have two var mp declaration. Try to remove the first one, var mp:MovieClip;. If it doesn't work, check your Flash Library carefully, be sure that MP_00 is a name available. If it's a MovieClip, check that it is exported for ActionScript. If it's an instance name, check that it's not used twice.
EDIT.
My suggestion is :
1- Change all references of mp to mp1. Maybe there is a conflict with an instance "...an object on the stage with the same name as an object in your library."
2- var mp1:MP_00; instead of var mp:MovieClip; in the declaration section.
3- Put the mp1 = new MP_00(); back in the startGame() function
4- Be sure that your new mp1 variable is everywhere you need and you have no more ref. to mp variable.
If... it's still doesn't work. I suggest : Change the name of your MovieClip linkage, like TestA, or whatever. Yes I know, a doubt on everything, but there is no magic, testing everything will show the problem for sure.
EDIT.
For mapMove() function...
First : be sure the speedUp() function is available, not in comments, and call it in your playGame() function. Your playerSpeed variable must have a value, so change : var playerSpeed = playerSpeed + 1; for playerSpeed = playerSpeed + 1;. Do not use var declaration twice for the same variable. (See var playerSpeed:Number; in header file.)
Beside... you have to know if the MP_00 clip on stage is YOUR mp1 clip. (I assumed you published all the code you have.)
Case A : MP_00 is on stage when you start your Clip.
If you actually see your MP_00 on screen, that mean you don't have to do mp1 = new MP_00(); and addchild(mp1);. It's already done for you (dragging a clip from library and giving a name instance, is the same as doing new and addchild).
Find the instance name (or give one). You should get your instance name and move your object (here the instance name is mp1):
mp1.y = mp1.y - playerSpeed;
Case B : MP_00 is NOT on stage when you start your Clip.
Do :
1- your declaration : var mp1:MP_00;
2- allocation memory : mp1 = new MP_00();
3- add to the display list : addchild(mp1);
4- "Shake it bb" : mp1.y = mp1.y - playerSpeed; or mp1.y -= playerSpeed;
I don't know what is your knowledge level exactly, so I tried to put everything. Sorry if it's too much.

Continuos Timer and object for a game AS3

I am currently working on a game where you need to survive as long as possible while dodging questions that come your way. (all with AS3)
At the moment I am going from 1 scene to another in between the game field and the question field, but everytime I go to the question scene the timer in the game scene resets itself. I was wondering if it was possible to have the timer continue while being in the question scene?
Also I have a movable character in between the menus which incidentally are also made in different scenes and the player is able to move him around, and I would very much like him to stay in the last position he was in the next screen, as in I move him to the top right in the main menu and when I go to the options menu I want him to still be in the top right and not in his initial position.
As for my timer this is the code I am using at the moment:
import flash.utils.Timer;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.globalization.DateTimeFormatter;
var timer:Timer = new Timer(100);
timer.start();
timer.addEventListener(TimerEvent.TIMER, timerTickHandler);
var timerCount:int = 0;
function timerTickHandler(Event:TimerEvent):void
{
timerCount += 100;
toTimeCode(timerCount);
}
function toTimeCode(milliseconds:int) : void {
//create a date object using the elapsed milliseconds
var time:Date = new Date(milliseconds);
//define minutes/seconds/mseconds
var minutes:String = String(time.minutes);
var seconds:String = String(time.seconds);
var miliseconds:String = String(Math.round(time.milliseconds)/100);
//add zero if neccecary, for example: 2:3.5 becomes 02:03.5
minutes = (minutes.length != 2) ? '0'+minutes : minutes;
seconds = (seconds.length != 2) ? '0'+seconds : seconds;
//display elapsed time on in a textfield on stage
timer_txt.text = minutes + ":" + seconds+"." + miliseconds;
}
And my character is using this code:
/* Move with Keyboard Arrows
Allows the specified symbol instance to be moved with the keyboard arrows.
Instructions:
1. To increase or decrease the amount of movement, replace the number 5 below with the number of pixels you want the symbol instance to move with each key press.
Note the number 5 appears four times in the code below.
*/
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
rutte.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
rutte.y -= 5;
}
if (downPressed)
{
rutte.y += 5;
}
if (leftPressed)
{
rutte.x -= 5;
rutte.scaleX = 1; // face left
}
if (rightPressed)
{
rutte.x += 5;
rutte.scaleX = -1; // face right
}
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = true;
break;
}
case Keyboard.DOWN:
{
downPressed = true;
break;
}
case Keyboard.LEFT:
{
leftPressed = true;
break;
}
case Keyboard.RIGHT:
{
rightPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = false;
break;
}
case Keyboard.DOWN:
{
downPressed = false;
break;
}
case Keyboard.LEFT:
{
leftPressed = false;
break;
}
case Keyboard.RIGHT:
{
rightPressed = false;
break;
}
Thank you in advance for all the help you can give me.
Kind Regards.
in flash there is a fundamental aspect of how timeline and scenes works. Once you move away from a frame to another frame, The content of the frame and it's properties/states/actions are gone and reseted.
Personally I recommend you use a single scene with a timeline divided into frames labeled, there you can specify a layer for the actions and global variables, one for the user interface and another one for the specific actions of each frame. example:
So you never lose the reference of variables because the frame is not constantly recreated, all your important actions, including you timer, should be in your first frame.
I was testing, here you can see a working example: http://db.tt/FZuQVvt3. Here you can download the FLA file to be used as a base for your project: http://db.tt/RHG9G5lo

Error: #1009: Type Error (Line #114)

I'm sort of a noob to flash, but I am programming a game right now, and I am trying to make my character move but i am getting error #1009 Here is my code in my "GameState".
Basically it errors out on any Keypress, I have my character named player (Player in the library) and it has another movie clip within it named WalkDown (I gave it an instance name of walkDown on the timeline) I am not really sure whats going on. Specifically it errors out on the line where its calling the frame name. Any help would be appreciated!
package {
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.geom.Point;
public class GameState extends MovieClip {
private var player:MovieClip;
private var walking:Boolean = false;
// is the character shooting
//private var shooting:Boolean = false;
// wlaking speed
private var walkingSpeed:Number = 5;
private var xVal:Number = 0;
private var yVal:Number = 0;
public function GameState() {
// constructor code
player = new Player();
addChild(player);
player.x = 300;
player.y = 300;
player.gotoAndStop("stance");
this.addEventListener(Event.ADDED_TO_STAGE, initialise);
}
private function initialise(e:Event){
// add a mouse down listener to the stage
//addEventListener(MouseEvent.MOUSE_DOWN, startFire);
// add a mouse up listener to the stage
//addEventListener(MouseEvent.MOUSE_UP, stopFire);
player.addEventListener(Event.ENTER_FRAME,motion);
stage.addEventListener(KeyboardEvent.KEY_UP,onKey);
// add a keyboard down listener
stage.addEventListener(KeyboardEvent.KEY_DOWN, offKey);
stage.focus = stage;
// Add keyboard events
}
private function motion(e:Event):void{
// if we are currently holding the mouse down
//if (shooting){
//FIRE
//fire();
//}
player.x += xVal;
player.y += yVal;
}
//private function startFire(m:MouseEvent){
//shooting = true;
//}
//private function stopFire(m:MouseEvent){
//shooting = false;
//}
private function onKey(evt:KeyboardEvent):void
{
trace("key code: "+evt.keyCode);
switch (evt.keyCode)
{
case Keyboard.W :
yVal = walkingSpeed;
if (! walking)
{
trace("walking up");
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.S :
yVal = - walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.A :
xVal = walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.D :
xVal = walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
}
}
private function offKey(evt:KeyboardEvent):void
{
switch (evt.keyCode)
{
case Keyboard.W :
//for now just reset velocity to zero
yVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.S :
//for now just reset velocity to zero
yVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.A :
//for now just reset velocity to zero
xVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.D :
//for now just reset velocity to zero
xVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
}
}
// Players Motion
private function fire():void{
var b= new Bullet();
// set the position and rotation of the bullet
b.rotation = rotation;
b.x = x;
b.y = y;
// add bullets to list of bullets
MovieClip(player).bullets.push(b);
// add bullet to parent object
player.addChild(b);
// play firing animation
player.shooting.gotoAndPlay("fire");
}
}
}
You were saying the Error #1009 ( Cannot access a property or method of a null object reference ) arises when you do
player.walkDown.gotoAndPlay("walking");
If so, that is because you have to first go to the frame where the WalkDown MovieClip is in before you can access it.
If say your "stance" frame is in frame 1 and your WalkDown MovieClip is in frame 2. Your code in the onKey function should look like:
case Keyboard.W :
yVal = walkingSpeed;
if (! walking)
{
trace("walking up");
player.gotoAndStop(2); // player.walkDown is now accessible //
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;