How can we control behavior of individual movie clips added randomly to stage from an array [as3] - actionscript-3

The code below adds a movie clip to the stage randomly from an array of movie clips. Once a movie clip is added to stage it moves horizontally on an x axis by echoing a corresponding sound clip. But my problem is, only the same sound clip is being played for any of the movie clips added on stage. The reason why its happening is of course because of the line:
var mc:MovieClip = new enemies[printArray[p]];
Can anyone please tell me how i can individually control the behavior of each movie clip that falls within "var mc". Instead of writing something like:
if(mc.x <= -100) { Enem1Timer.stop()} else if(mc.x <= 570){ Enem1Timer.start() }
is there a way to write like:
if(Enem1.x <= -100).....
Any help is most welcome. Thanx in advance.
import flash.utils.Timer;
import flash.display.MovieClip;
var sound1:Letter1 = new Letter1();
var sound2:Letter2 = new Letter2();
var sound3:Letter3 = new Letter3();
var sound4:Letter4 = new Letter4();
var sound5:Letter5 = new Letter5();
var sound6:Letter6 = new Letter6();
var printArray:Array = [0, 1, 2, 3, 4, 5];
var enemies:Array = [Enem1, Enem2, Enem3, Enem4, Enem5, Enem6];
for(var n:int = 0; n <= 6; n++)
{
var randNo:int = int(Math.random() * 6);
printArray.push(randNo);
}
var Enem1Timer:Timer = new Timer(1000, 1);
Enem1Timer.addEventListener(TimerEvent.TIMER, playA1);
function playA1(e:TimerEvent):void
{sound1.play();}
for(var p:int = 0; p < printArray.length; p++)
{
trace(printArray[p]);
var mc:MovieClip = new enemies[printArray[p]];
addChild(mc);
mc.x = 600; mc.y = 200;
stage.addEventListener(Event.ENTER_FRAME, loop)
function loop(e:Event){
if(mc.x <= -100) { Enem1Timer.stop()} else if(mc.x <= 570){ Enem1Timer.start() }
mc.x -= 3;
}}

if you mcs are already created in the array (not null) then you should remove "new" since you're accessing it, not creating it:
var mc:MovieClip = enemies[p] as MovieClip;

Related

Movieclip names

I'm having troubles with AS3 and addChild methods.
First, I create an object called "container". Inside container I create an empty object with an empty MovieClip from library called "holder". Then I create the Movieclips inside the container.holder
But I cannot access to the MovieClips! Anyone knows why? Here is the code:
// Creating object
var container:Object {
x: 30,
y: 30
}
// Empty object
var eObject: MovieClip = new MovieClip();
container.holder = eObject;
// Creating Movieclips
var mc : MovieClip;
for (var i : int = 0; i < 5; i++) {
var mc: _myClip = new _myClip(); // _myClip is a MC from my library.
mc.name = "myMc"+ i;
mc.x = 10;
container.holder.addChild(mc);
}
// Calling MovieClips
container.holder["myMc"+3].x = 40; // Nothing happens
You can reduce the complexity and needless usage of the name property by using an Array:
var items:Array = [];
for (var i:int = 0; i < 5; i++) {
var mc:_myClip = new _myClip();
container.holder.addChild(mc);
items.push(mc);
}
items[2].x = 40;

event.localX of a MovieClip regardless of any other DisplayObject over/under/inside

Here is an example:
var table:Table = new Table();
stage.addChild(table);
//table covers the whole stage
for (var i:int = 0; i<= 10; i++){
var book:Book = new Book();
book.x = Math.random() * stage.stageWidth;
book.y = Math.random() * stage.stageHeight;
if (Math.random() < .5){
stage.addChild(book)
}
else {
table.addChild(book)
}
stage.addEventListener(MouseEvent.CLICK, clicked);
function clicked(event:MouseEvent){
trace(event.localX, event.localY);
}
what i need here is the localX or localY OF THE TABLE, not anything else.
so the general question is "how to return event.localX of a certain MovieClip regardless of any other DisplayObject over/under/inside it, without setting the mouseChildren to false (as I need them to be enabled)"
You can use DisplayObject's globalToLocal method to convert a Point from being relative to the stage to being relative to the table object.
function clicked(event:MouseEvent){
var globalPt:Point = new Point(event.stageX, event.stageY);
var tablePt:Point = table.globalToLocal(globalPt);
trace(tablePt.x, tablePt.y);
}

drag and drop with target

I am kinda new in flash as3, however am doing courseware app that involves dragging words into their appropriate targets with scores if correctly matched and also includes a 20sec timer that an exercise should be done. But my problem is after i drag the words correct to their positions and get relevant score (I use 10 marks each correct answer) still I can drag the word and score again and again using every dragged word (i.e I want to unable dragged words from dragging) which makes a user to score more exceeding the higher score (i.e 90 marks because there 9 words to drag).
Here is my coding;
stop();
import flash.events.MouseEvent;
import flash.events.TimerEvent;
import flash.utils.Timer;
var myscore1 = 0; score.text = myscore1+"";
var hitArray:Array = new Array(love_tgt, am_stud_tgt, living_tgt, is_improv_tgt, speak_tgt,
means_tgt, are_help_tgt, want_tgt, miss_tgt);
var dropArray:Array = new Array(love, am_stud, living, is_improv, speak, means, are_help,
want, miss);
var positionsArray:Array = new Array();
for (var i:int = 0; i < dropArray.length; i++) {
dropArray[i].buttonMode = true;
dropArray[i].addEventListener(MouseEvent.MOUSE_DOWN, mdown);
dropArray[i].addEventListener(MouseEvent.MOUSE_UP, mUp);
positionsArray.push({xPos:dropArray[i].x, yPos:dropArray[i].y});
}
function mdown(e:MouseEvent):void {
e.currentTarget.startDrag();
setChildIndex(MovieClip(e.currentTarget), numChildren - 1);
}
function mUp(e:MouseEvent):void {
var dropIndex:int = dropArray.indexOf(e.currentTarget);
var target:MovieClip = e.currentTarget as MovieClip;
target.stopDrag();
if (target.hitTestObject(hitArray[dropIndex])) {
myscore1+=10;
score.text = myscore1+"";
target.x = hitArray[dropIndex].x;
target.y = hitArray[dropIndex].y;
}else{
target.x = positionsArray[dropIndex].xPos;
target.y = positionsArray[dropIndex].yPos;
}
}
var myTimer1:Timer = new Timer(1000);
myTimer1.addEventListener(TimerEvent.TIMER, countdownHandler1);
function countdownHandler1(event:TimerEvent):void{
countdown.text = 20-myTimer1.currentCount+" s remaining";
if(myTimer1.currentCount==20){
gotoAndStop(46);
} }
myTimer1.start();
}
You still can drag the objects because they still have event listeners. All you need to do is to remove it.
if (target.hitTestObject(hitArray[dropIndex])) {
myscore1+=10;
score.text = myscore1+"";
target.x = hitArray[dropIndex].x;
target.y = hitArray[dropIndex].y;
//add these 2 lines---------------------------------------------
target.removeEventListener(MouseEvent.MOUSE_DOWN, mdown);
target.removeEventListener(MouseEvent.MOUSE_UP, mUp);
//--------------------------------------------------------------
}else{
target.x = positionsArray[dropIndex].xPos;
target.y = positionsArray[dropIndex].yPos;
}

Remove sprite from stage in as3

I have this code for a message to appear on stage when player finishes drag and drop. I would like this sprite to be removed when a button is clicked for the next frame. Can someone help me with the code?
stage.addEventListener(Event.ENTER_FRAME, EntFrame);
function EntFrame (e:Event):void
{
if (CntP1+CntP2+CntP3+CntP4+CntP5+CntP6+CntP7+CntP8 == 40)
{
var w:int = 400, h:int = 200;
var win:Sprite = new Sprite();
win.name = "Mywin";
addChild(win);
// draw rounded rect with subtle vertical linear gradient fill and blue stroke
win.graphics.lineStyle(4,0x0077ff);
var mat:Matrix = new Matrix();
mat.createGradientBox(w, h, 90 * (Math.PI / 180));
win.graphics.beginGradientFill(GradientType.LINEAR,[0xffffff,0xeeeeee],[1.00,1.00],[0,255],mat);
win.graphics.drawRoundRect(0,0,w,h,15,15);
// show center "YOU WIN!" text
var tf:TextField = new TextField();
tf.autoSize = TextFieldAutoSize.LEFT;
tf.antiAliasType = AntiAliasType.ADVANCED;
tf.defaultTextFormat = new TextFormat("Arial, Verdana",36,0x454545,true);
tf.text = "Κέρδισες!";
tf.selectable = false;
win.addChild(tf);
tf.x = w/2 - tf.width/2;
tf.y = h/2 - tf.height/2;
// add a drop shadow
var dropShadow:DropShadowFilter = new DropShadowFilter(3,45,0,.35,8,8,1,3);
win.filters = [dropShadow];
// center the graphic
win.x = stage.stageWidth/2 - win.width/2;
win.y = stage.stageHeight/2 - win.height/2;
}
}
Your code isn't written well and needs rewriting to ensure reuse or scalability of your project, but here's a quick way out.
make a holder Sprite, something like
var messageHolder:Sprite = new Sprite();
addChild(messageHolder);
add all the messages to that holder in any fashion you like. When you need to erase the contents of that holder, call following method:
function clearHolderContents(holder:DisplayObjectContainer):void
{
if (holder.numChildren < 1)
return; // no need to continue this method if the target is empty
for (var i:int = holder.numChildren - 1; i >= 0; i--)
removeChild(holder.getChildAt(i));
}
This method can clear contents of any DisplayObjectContainer => use it for your messageHolder:
clearHolderContents(messageHolder);
Hope that helps!

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.