LoadMovieclips Array Click Btn Array - actionscript-3

How can click on any button to load the array into the concrete contents of the array Teddy I Grateful (Load Movieclips Array Click button Array)
var teddy:Array = [home,about,products,services,contact];
var l:int = teddy.length;
for (var j:int = 0; j < l; j++) {
var mc1=new teddy[j];
var mc2=new teddy[1];
teddy[j].buttonMode = true;
var Btn:Array = [Btnhome,Btnabout,Btnproducts,Btnservices,Btncontact];
var W:int = Btn.length;
for (var i:int = 0; i < W; i++) {
var mc:MovieClip = new Btn[i];
mc.buttonMode = true;
mc.x=400+i*100;
mc.y=600+i;
mc.addEventListener(MouseEvent.CLICK, clickHandler);
addChild(mc);
}
}
function clickHandler(event:MouseEvent):void {
switch (event.currentTarget) {
case mc :
addChild(mc1);
trace("home");
mc1.x=400;
mc1.y=200;
break;
case mc :
addChild(mc2);
trace("about");
mc2.x=400
mc2.y=300
break;
case products_mc :
trace("products");
break;
case services_mc :
trace("services");
break;
case contact_mc :
trace("contact");
break;
}}

if [home,about,products,services,contact],
and [Btnhome,Btnabout,Btnproducts,Btnservices,Btncontact] are object instance Name's, then your code is wrong.
But in that case, you can position them once, then each time set them visible/invisible with this;
// set as invisible
myArray[i].visible = false;
// set as visible
myArray[i].visible = true;
Else, if you have to re-create them each time, then you must specify an Object Class for your objects, and call them with their object classes
var mc = new myObjClass();
And to give object classes names that you can refer from your code, do the following;
In your Library panel,
Select the MovieClip you want to create instances of,
[Right-Click] > Properties...
Check Export for ActionScript
And give Class name below. Then use that class name in your code to create new MovieClip instances of it every time.
Depending on your Flash version that process can be slightly different. But you can google it anyway.
Hope that helps.

Okay I will try to help you one more time. But you must talk to the people trying to help you. If you dont understand just ask. Also at least up-vote useful answers to your questions or mark as correct if it works okay. Otherwise no-one wants to type tutorials (because there is Google and ActionScript manual for that).
The best way to test my shown code is... Make a new blank FLA file and save to some folder. Now go to Properties (ctrl+F3) and in the Class: box type in there Array_buttons_v1 (press enter and save FLA again). Now you can click the pencil icon next to Class: box to edit your Class document. You will replace that auto-code with mine shown below.. (in photo: MyClass becomes Array_buttons_v1)
image borrowed from: Adobe.com
You will also need 5 movieClips in your library (ctrl+L). That is one movieClip to use as button MC and then four other movieClips to be added on stage when you click. Each one in Library must be right-clicked and choose "properties" then in Linkage section tick Export for Actionscript and use the following name in Class box shown there..
one small MC as button use: btn_MC (later we make MC clickable just like a real button)
other four MCs to add when button clicked use: MC1, MC2, MC3, MC4
Now you can use the main Properties (crtl+F3) to click the pencil icon (see pencil in photo) and delete all that automatic code and paste this code there.. (try to understand what code is doing, not just copy+paste..). It makes four buttons from MC class name btn_MC into some array and then loads other four MCs to array then from Mc array can add to screen too. Hope it helps
package
{
//** You will need more IMPORTS as you use other Flash features (APIs)
//** But these two is enough here.. check AS3 manual or tutorials for what to add
import flash.display.MovieClip;
import flash.events.*;
public class Array_buttons_v1 extends MovieClip
{
public var MC_Array:Array = []; //new array is empty
public var Btn_Array:Array = [];
public var MC_0 : MC1 = new MC1();
public var MC_1 : MC2 = new MC2();
public var MC_2 : MC3 = new MC3();
public var MC_3 : MC4 = new MC4();
public var btn_0 : btn_MC = new btn_MC();
public var btn_1 : btn_MC = new btn_MC();
public var btn_2 : btn_MC = new btn_MC();
public var btn_3 : btn_MC = new btn_MC();
public var mClips_holder : MovieClip = new MovieClip;
public var buttons_holder : MovieClip = new MovieClip;
public function Array_buttons_v1()
{
//** Update MC array.. items are counted from 0,1,2,3 (NOT 1,2,3,4)
MC_Array = [ MC_0, MC_1, MC_2, MC_3 ]; //meaning array pos [ 0, 1, 2, 3 ]
stage.addChild( mClips_holder ); //will hold
mClips_holder.y = 70; //move down so its not blocking anything
//** Update Buttons array
Btn_Array = [ btn_0, btn_1, btn_2, btn_3 ];
stage.addChild( buttons_holder ); //put Button holder on stage
//buttons_holder.addChild( Btn_Array [0] ); //put Buttons inside holder
var insert_pos:int = 0; //will use as screen "adding position" for buttons
//** To add all in array.. we start from pos of 0 and count up to 3
//** For every count number we do instructions inside { } until count finished
for (var arr_pos:int = 0; arr_pos <= 3; arr_pos++) //create some counter
{
trace("position inside the array is now : " + arr_pos);
//** setup instance Names for movieClips inside the MC Array
//** later you can access each one by name using "getChildByName" as MC_1 or MC_2 etc..
MC_Array[arr_pos].name = "MC_" + ( String(arr_pos) );
//** setup Buttons (names, clicked functions etc )..
Btn_Array[arr_pos].name = "button_" + ( String(arr_pos) );
Btn_Array[arr_pos].buttonMode = true; //make clickable before adding to screen
Btn_Array[arr_pos].addEventListener(MouseEvent.CLICK, button_Clicked);
buttons_holder.addChildAt( Btn_Array [arr_pos], arr_pos ); //add to container
buttons_holder.getChildAt(arr_pos).x = insert_pos;
trace("pos of btn is now : " + buttons_holder.getChildAt(arr_pos).x);
//update the adding position amount
insert_pos += 50; //add +50 pixels distance for next item
} //end For loop
}
public function button_Clicked ( evt :MouseEvent ) : void
{
//** Use "evt" because it matches with above "evt:MouseEvent" for access
trace( "Button name: " + evt.currentTarget.name + " ..was clicked" );
//** Now you can use IF statement to run another function(s)
//if (evt.currentTarget.name == "button_0") { some_Test(); }
//** or Use SWITCH statement (better and easier)
switch (evt.currentTarget.name)
{
case "button_0" :
//mClips_holder.addChild(MC_0); //** can be done like this ..
mClips_holder.addChild( MC_Array[0] ); //but you wanted from array so do this way..
mClips_holder.getChildByName("MC_0").x = 0;
some_Test(); //to do some other function
//** to stop this button listening for mouse clicked
//Btn_Array[0].removeEventListener(MouseEvent.CLICK, button_Clicked);
break;
case "button_1" :
mClips_holder.addChild(MC_1);
mClips_holder.getChildByName("MC_1").x = 40;
//Btn_Array[1].removeEventListener(MouseEvent.CLICK, button_Clicked);
break;
case "button_2" :
mClips_holder.addChild(MC_2);
mClips_holder.getChildByName("MC_2").x = 80;
//Btn_Array[2].removeEventListener(MouseEvent.CLICK, button_Clicked);
break;
case "button_3" :
mClips_holder.addChild(MC_3);
mClips_holder.getChildByName("MC_3").x = 120;
break;
} //end Switch/Case
}
public function some_Test ( ) : void
{
trace(" ### This is some other function... do extra things in this section");
//your extra code here..
}
}
}

Related

AS3 Editing event.target after being clicked befor executing gotoAndPlay("abc");

Greetings stackoverflow members,
i have 3 animated movieclips nested in a movieclip. What I'm trying to do is to get the name of the instance clicked and edit it befor applying gotoAndPlay. I can get the name but when ever I try to edit it I'm getting the Error:
Symbol 'Buttons MC', Layer 'Actions', Frame 1, Line 30 1061: Call to a possibly undefined method gotoAndPlay through a reference with static type String.
Here's my code so far:
[Bindable] var targetName:String;
var _userInput:String = new String();
_userInput = targetName;
//array for buttons
var btnArray:Array = [INS_Btn1, INS_Btn2, INS_Btn3];
//add eventlistiners
for(var i:uint=0; i<btnArray.length; i++) {
btnArray[i].addEventListener(MouseEvent.ROLL_OVER, bRollover);
btnArray[i].addEventListener(MouseEvent.ROLL_OUT, bOut);
btnArray[i].addEventListener(MouseEvent.CLICK, bClick);
btnArray[i].buttonMode=true;
}
//btn over state
function bRollover(event:MouseEvent):void{
event.target.gotoAndPlay("Over");
}
//btn out state
function bOut(event:MouseEvent):void{
event.target.gotoAndPlay("Out");
}
//btn click state
function bClick(event:MouseEvent):void{
targetName = event.target +("_ani")
targetName.gotoAndPlay("Active");
}
What I want is that the MC clicked should go and play the animation of an onther MC. Best I should mention that I'm a beginner in AS3.
targetName is a String and of course you can't gotoAndPlay on a string :) Besides of that, event.target will return the object that you've clicked and not its name. And the targetName does not need to be bindable if you don't do anything special with it besides of this code.
So I assume you want a movieclip with the instance name INS_Btn1_ani to be played when you click on the INS_Btn1 button? First, make sure your buttons have the name property set (to make it easier, set the name as "INS_Btn1", "INS_Btn2" etc as well.
INS_Btn1.name = "INS_Btn1";
Then you would do it like that:
function bClick(event:MouseEvent):void
{
targetName = event.target.name + "_ani"; // this will become INS_Btn1 + _ani = INS_Btn1_ani
// Now you need to let the movieclip with the name "INS_Btn1_ani" play
this[targetName].gotoAndPlay("Active");
}
So after understanding the answer from Philarmon I've solved the problem. In case someone has the same/similar problem here's what I've done to get it working:
var targetName:String;
var _userInput:String = new String();
_userInput = targetName;
//array for buttons MCs
var btnArray:Array = [INS_btn1, INS_btn2];
var aniArray:Array = [INS_btn1_ani, INS_btn2_ani];
//add eventlistiners
for(var i:uint=0; i<btnArray.length; i++) {
btnArray[i].addEventListener(MouseEvent.ROLL_OVER, bRollover);
btnArray[i].addEventListener(MouseEvent.ROLL_OUT, bOut);
btnArray[i].addEventListener(MouseEvent.CLICK, bClick);
btnArray[i].buttonMode=true;
}
//btn over state
function bRollover(event:MouseEvent):void{
targetName = event.currentTarget.name + "_ani";
this[targetName].gotoAndPlay("Over");
}
//btn out state
function bOut(event:MouseEvent):void{
targetName = event.currentTarget.name + "_ani";
this[targetName].gotoAndPlay("Out");
}
//on clicked
function bClick(event:MouseEvent):void{
//add listeners for unclicked
for (var i:uint=0;i<btnArray.length; i++){
btnArray[i].addEventListener(MouseEvent.ROLL_OUT, bOut);
btnArray[i].addEventListener(MouseEvent.ROLL_OVER, bRollover);
//stopping animation
aniArray[i].gotoAndStop("Out");
}
//remove Eventlistener when clicked
event.target.removeEventListener(MouseEvent.ROLL_OUT, bOut);
event.target.removeEventListener(MouseEvent.ROLL_OVER, bRollover);
targetName = event.currentTarget.name + "_ani";
this[targetName].gotoAndStop("Active");
}
As you can see I've added a "sticky" function to keep the mc on click state.

flash as3 - assigning a set of event handlers to a set of movieclips

I have a movieclip in my library which contains a set of menu controls. Each control has a series of actions it will perform on rollover, rollout, and click, plus a few properties that should always be set (buttonMode, mouseChildren).
In my class, instead of selecting each button's event listeners, is there a way to apply a set of event listeners and properties to all of the clips? They are at different levels and locations within the menu, but they all have the same actions: gotoAndPlay("over")", buttonMode = true, etc.
Here's how my class is set up:
package {
import flash.display.*;
import flash.events.*;
import com.greensock.*;
import com.greensock.easing.*;
public class Main extends MovieClip {
public var menuInstance:PanoMenu;
private var menuTopRef;
public function Main() {
menuInstance = new PanoMenu();
menuInstance.x = -43;
menuInstance.y = 23;
menuTopRef = menuInstance.menuTop;
menuTopRef.buttonMode = true;
menuTopRef.addEventListener(MouseEvent.CLICK,menuTopClick); //MH - want to do this for all clips in the menu, with their own unique callbacks specified
addChild(menuInstance);
trace ("main");
}
private function menuTopClick(e:MouseEvent){
trace ("top click");
}
}
}
While Reshape Media's answer is a good way to handle the Click events, the button behavior should probably be handled by creating a Class and applying it to all of your button-ish MovieClips. Or, the old school way is to just make a button Symbol (which will be an instance of SimpleButton) that pretty much works like you want without any extra code.
Based on your situation, you don't need different handlers. What you can do is send ALL events from ALL buttons (in the menu) to a single handler and then do a switch case to check the name of the button and go from there.
//random menu items
var menu_item_1:Sprite = new Sprite;
var menu_item_2:Sprite = new Sprite;
var menu_item_3:Sprite = new Sprite;
//give them unique names
menu_item_1.name = 'item 1';
menu_item_2.name = 'item 2';
menu_item_3.name = 'item 3';
//define an array and add the SAME listener
var menu_items:Array = [menu_item_1,menu_item_2,menu_item_3];
for(var i:Number = 0; i<menu_items.length; i++){
var item:Sprite = menu_items[i] as Sprite;
item.addEventListener(MouseEvent.CLICK,onClick);
}
//listen for all button clicks
//do a switch case to map the clicks
function onClick(e:MouseEvent):void{
switch(e.target.name){
case 'item 1':
//do something
break;
case 'item 2':
//do something
break;
case 'item 2':
//do something
break;
}
}

AS3 - Dynamically re-populate a series of textFields held within a group of MovieClips

I’ve come across a problematic issue with some functionality I’m attempting to develop in ActionScript3 on the Flash Professional CS5 platform and was wondering if anybody could point me in the right direction with it?
Background
Within my ActionScript Class, I have written a MouseEvent function which dynamically adds multiple instances of the same MovieClip (user_shape) on to the stage in the formation of a shape that the user has designed in an earlier stage of the program.
This shape effect is achieved through a For Loop that loops through the entire length of a Multi-Dimensional Boolean based array looking for an instance of true (determined by the user’s actions earlier) and then adding a MovieClip to the stage if this is the case.
Each group of MovieClips added with a single click, while always having the same instance name (user_shape), is always assigned a unique ID, which I've set up by including a numerical variable that increments up by 1 each time I add the batch of 'user_shape' MovieClips through left click to the stage.
The user can pick from up to eight different colours to assign to their shape (via selection boxes) before adding it to the stage. For each of these eight colours I have added a numerical variable (shapeCounterBlue, shapeCounterRed etc.) which basically counts ++ every time I add a shape of a certain colour to the stage and likewise it counts -- if I chose to remove a shape.
As a shape is added through my main function I attach a dynamic textField to each MovieClip and populate it with the variable counter number for the particular colour I have selected (see image below).
Problem
OK, so here is my issue. I need my unique number (displayed in white) for each coloured shape to dynamically re-populate and update when I remove a shape from the stage. As you can see in the image I’ve attached, if I were to remove the second blue shape, my third blue shape’s numbers would need to revert from 3 to 2.
Likewise if I had six red shapes on the stage and I decided to remove the third one, then shapes 4,5,6 (before 3 is deleted), would need to have their numbers changed to 3,4,5 respectively.
Or I could have four green shapes and remove the first shape; this would mean that shapes 2,3,4 would actually need to change to be 1,2,3.
You get the idea. But does anybody know how I could achieve this?
My problem has further been hampered by the fact that the textFields for each MovieClip are added dynamically through my For Loop to the user_shape Child. This means that within my AS class, I haven’t been able to publicly declare these textFields and access the values within them, as they only exist in the For Loop used in my add shape function and no where else.
Many thanks in advance.
as to the targeting dynamically created text fields. In your loop assign a name that you can later access.
for(i:int=0;i<myArray.length;i++){
var txt:TextField = new TextField();
txt.name = "txt_" + i;
this.addChild(txt);
}
Then to access your textfields outside the loop target them like this:
var targetTxt:TextField = this.getChildByName("txt_10");
UPDATE
Ok so I had some time and went ahead and solved your entire problem
(Download Source FLA/AS files)
Ok so there are some MCs in the library that I call in my code. I created a Box MC that has a label textfield, a border, and a background MC that I can target to color.
I created a countColors() that loops over all the boxes once you have click on one (triggered from a mouseEvent within each box). It counts the different colors totals in an array and then sends a custom event to let all the boxes know they can fetch the color totals to update their labels.
I hope this helps.
main.as
package {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;
public class main extends MovieClip {
public static var ROOT:MovieClip;
public var totalBoxes:int = 100;
public var boxContainer:Sprite;
public static var colorArray:Array = [0xFF0000, 0x0000FF, 0x00FF00];
public static var colorCount:Array = [0,0,0];
public static var currentColor = 0;
public function main() {
// set ref to this
ROOT = this; // so I can get back to it from the boxes
// color selection
redBtn.addEventListener(MouseEvent.CLICK, chooseColor);
blueBtn.addEventListener(MouseEvent.CLICK, chooseColor);
greenBtn.addEventListener(MouseEvent.CLICK, chooseColor);
// add box container to stage
boxContainer = new Sprite();
boxContainer.x = boxContainer.y = 10;
this.addChild(boxContainer);
var row:int=0;
var col:int=0;
for(var i:int=0; i < totalBoxes; i++){
var box:Box = new Box();
box.x = col * box.width;
box.y = row * box.height;
box.name = "box_" + i;
box.ID = i;
box.updateDisplay();
boxContainer.addChild(box);
if(col < 9){
col++;
}else{
col = 0;
row++;
}
}
}
private function chooseColor(e:MouseEvent):void
{
var btn:MovieClip = e.currentTarget as MovieClip;
switch(btn.name)
{
case "redBtn":
currentColor=0;
break;
case "blueBtn":
currentColor=1;
break;
case "greenBtn":
currentColor=2;
break;
}
// move currentColorArrow
currentColorArrow.x = btn.x;
}
public function countColors():void
{
colorCount = [0,0,0]; // reset array
for(var i:int=0; i < totalBoxes; i++){
var box:Box = boxContainer.getChildByName("box_" + i) as Box;
if(box.colorID > -1)
{
colorCount[ box.colorID ]++;
}
}
// send custom event that boxes are listening for
this.dispatchEvent(new Event("ColorCountUpdated"));
}
}
}
Box.as
package {
import flash.display.MovieClip;
import flash.geom.ColorTransform;
import flash.events.MouseEvent;
import flash.events.Event;
public class Box extends MovieClip {
public var ID:int;
public var colorID:int = -1;
private var active:Boolean = false;
private var bgColor:Number = 0xEFEFEF;
public function Box() {
this.addEventListener(MouseEvent.CLICK, selectBox);
main.ROOT.addEventListener("ColorCountUpdated", updateCount); // listen to root for custom event to update display
}
public function updateDisplay() {
if(active == false){
boxLabel.htmlText = "<font color='#000000'>"+ ID +"</font>";
}else{
boxLabel.htmlText = "<font color='#FFFFFF'>"+ main.colorCount[colorID] +"</font>";
}
var myColorTransform = new ColorTransform();
myColorTransform.color = bgColor;
boxBG.transform.colorTransform = myColorTransform;
}
private function selectBox(e:MouseEvent):void
{
// set bgColor
if(active == false){
bgColor = main.colorArray[main.currentColor];
colorID = main.currentColor;
}else{
bgColor = 0xEFEFEF;
colorID = -1;
}
// set active state
active = !active // toggle true/false
main.ROOT.countColors();
}
private function updateCount(e:Event):void
{
updateDisplay();
}
}
}

use 1 object multiple times in as3?

I'm trying to make something like bookmarks, I have 1 note on the stage and when the user clicks it, it starts to drag and the users drops it where they want. the problem is I want these notes to be dragged multiple times.. here is my code:
import flash.events.MouseEvent;
//notess is the instance name of the movie clip on the stage
notess.inputText.visible = false;
//delet is a delete button inside the movie clip,
notess.delet.visible = false;
//the class of the object i want to drag
var note:notes = new notes ;
notess.addEventListener(MouseEvent.CLICK , newNote);
function newNote(e:MouseEvent):void
{
for (var i:Number = 1; i<10; i++)
{
addChild(note);
//inpuText is a text field in notess movie clip
note.inputText.visible = false;
note.x = mouseX;
note.y = mouseY;
note.addEventListener( MouseEvent.MOUSE_DOWN , drag);
note.addEventListener( MouseEvent.MOUSE_UP , drop);
note.delet.addEventListener( MouseEvent.CLICK , delet);
}
}
function drag(e:MouseEvent):void
{
note.startDrag();
}
function drop(e:MouseEvent):void
{
e.currentTarget.stopDrag();
note.inputText.visible = true;
note.delet.visible = true;
}
function delet(e:MouseEvent):void
{
removeChild(note);
}
any help will be appreciated.
You need to create a new instance of your note class when you drop, copy the location and other variables from the note you were dragging, add your new note to the stage, and return the dragging note to its original position.
Something like:
function drop($e:MouseEvent):void
{
$e.currentTarget.stopDrag();
dropNote($e.currentTarget as Note);
}
var newNote:Note;
function dropNote($note:Note):void
{
newNote = new Note();
// Copy vars:
newNote.x = $note.x;
newNote.y = $note.y;
// etc.
// restore original note.
// You will need to store its original position before you begin dragging:
$note.x = $note.originalX;
$note.y = $note.orgiinalY;
// etc.
// Finally, add your new note to the stage:
addChild(newNote);
}
... this is pseudo-code really, since I don't know if you need to add the new note to a list, or link it to its original note. If you Google ActionScript Drag Drop Duplicate, you will find quite a few more examples.
I think you are not target the drag object in drag function and problem in object instantiation
for (var i:Number = 1; i<numberOfNodes; i++) {
note = new note();
addChild(note);
...
....
}
function drag(e:MouseEvent):void{
(e.target).startDrag();
}
If you are dragging around multiple types of objects (eg. Notes and Images), you could do something like this, rather than hard coding the type of object to be instantiated.
function drop(e:MouseEvent):void{
// Get a reference to the class of the dragged object
var className:String = flash.utils.getQualifiedClassName(e.currentTarget);
var TheClass:Class = flash.utils.getDefinitionByName(className) as Class;
var scope:DisplayObjectContainer = this; // The Drop Target
// Convert the position of the dragged clip to local coordinates
var position:Point = scope.globalToLocal( DisplayObject(e.currentTarget).localToGlobal() );
// Create a new instance of the dragged object
var instance:DisplayObject = new TheClass();
instance.x = position.x;
instance.y = position.y;
scope.addChild(instance);
}

Multiple movieclips all go to the same spot; What am i doing wrong?

So I'm trying to shoot multiple bullets out of my body and it all works except I have an odd problem of just one bullet showing up and updating to set position for the new ones.
I have a move able player thats supposed to shoot and I test this code by moving the player and shooting. Im taking it step by step in creating this.
The result of tracing the bulletContainer counts correctly in that its telling me that movieclips ARE being added to the stage; I Just know it comes down to some kind of logic that im forgetting.
Here's My Code (The Bullet it self is a class)
UPDATE*
Everything in this code works fine except for I stated earlier some code seems reduntned because I've resorted to a different approaches.
BulletGod Class:
public class bulletGod extends MovieClip{
//Register Variables
//~Global
var globalPath = "http://127.0.0.1/fleshvirusv3/serverside/"
//~MovieCLips
var newBullet:bulletClass = new bulletClass();
//~Boolean
var loadingBulletInProgress:Number = 0;
var shootingWeapon:Number = 0;
//~Timers
var fireBulletsInterval = setInterval(fireBullets, 1);
var bulletFireEvent;
//~Arrays
var bulletArray:Array = new Array();
var bulletType:Array = new Array();
var bulletContainer:Array = new Array();
//~Networking
var netBulletRequest:URLRequest = new URLRequest(globalPath+"bullets.php");
var netBulletVariables:URLVariables = new URLVariables();
var netBulletLoader:URLLoader = new URLLoader();
//~Bullet Image Loader
var mLoader:Loader = new Loader();
var mRequest:URLRequest = new URLRequest();
public function bulletGod() {
//Load every bullet for every gun
//Compile data to be requested
netBulletVariables.act = "loadBullets"
netBulletRequest.method = URLRequestMethod.POST
netBulletRequest.data = netBulletVariables;
netBulletLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
netBulletLoader.addEventListener(Event.COMPLETE, getBulletImages);
netBulletLoader.load(netBulletRequest);
}
private function getBulletImages(bulletImageData:Event){
//Request every bullet URL image
//Set vars
var bulletData = bulletImageData.target.data;
//Load images
for(var i:Number = 0; i < bulletData.numBullets; i++){
bulletArray.push(bulletData["id"+i.toString()]);
bulletType.push(bulletData["bullet"+i.toString()]);
//trace(bulletData["id"+i]+"-"+bulletData["bullet"+i]);
}
//All the arrays have been set start firing the image loader/replacer
var imageLoaderInterval = setInterval(imageReplacer, 10);
}
private function imageReplacer(){
//Check to see which image needs replacing
if(!loadingBulletInProgress){
//Begin loading the next image
//Search for the next "String" in the bulletType:Array, and replace it with an image
for(var i:Number = 0; i < bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//Load this image
mRequest = new URLRequest(globalPath+"ammo/"+bulletType[i]);
mLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadImage);
mLoader.load(mRequest);
//Stop imageReplacer() while we load image
loadingBulletInProgress = 1;
//Stop this for() loop while we load image
i = 999;
}
}
}
}
private function loadImage(BlackHole:Event){
//Image has loaded; find which array slot it needs to go into
for(var i:Number = 0; i <= bulletType.length; i++){
if(getQualifiedClassName(bulletType[i]) == "String"){
//We found which array type it belongs to; now replace the text/url location with the actual image data
var tmpNewBullet:MovieClip = new MovieClip;
tmpNewBullet.addChild(mLoader);
//Add image to array
bulletType[i] = tmpNewBullet;
//Restart loadingBullets if there are more left
loadingBulletInProgress = 0;
//Stop for() loop
i = 999;
}
}
}
//###############################################################################################################################################
private function fireBullets(){
//If player is holding down mouse; Fire weapon at rate of fire.
if(shootingWeapon >= 1){
if(bulletFireEvent == null){
//Start shooting bullets
bulletFireEvent = setInterval(allowShooting, 500);
}
}
if(shootingWeapon == 0){
//The user is not shooting so stop all bullets from firing
if(bulletFireEvent != null){
//Strop firing bullets
clearInterval(bulletFireEvent);
bulletFireEvent = null
}
}
}
private function allowShooting(){
//This function actually adds the bullets on screen
//Search for correct bullet/ammo image to attach
var bulletId:Number = 0;
for(var i:Number = 0; i < bulletArray.length; i++){
if(bulletArray[i] == shootingWeapon){
//Bullet found
bulletId = i;
//End For() loop
i = 999;
}
}
//Create new bullet
//Create Tmp Bullet
var tmpBulletId:MovieClip = new MovieClip
tmpBulletId.addChild(newBullet);
tmpBulletId.addChild(bulletType[bulletId]);
//Add To Stage
addChild(tmpBulletId)
bulletContainer.push(tmpBulletId); //Add to array of bullets
//Orientate this bullet from players body
var bulletTmpId:Number = bulletContainer.length
bulletTmpId--;
bulletContainer[bulletTmpId].x = Object(root).localSurvivor.x
bulletContainer[bulletTmpId].y = Object(root).localSurvivor.y
//addChild(bulletContainer[bulletTmpId]);
}
//_______________EXTERNAL EVENTS_______________________
public function fireBullet(weaponId:Number){
shootingWeapon = weaponId;
}
public function stopFireBullets(){
shootingWeapon = 0;
}
}
}
BulletClass:
package com{
import flash.display.*
import flash.utils.*
import flash.net.*
import flash.events.*
public class bulletClass extends MovieClip {
public var damage:Number = 0;
public function bulletClass() {
//SOME MOVEMENT CODE HERE
}
public function addAvatar(Obj:MovieClip){
this.addChild(Obj);
}
}
}
Well ... if I may say so, this code looks quite wrong. Either something is missing from the code or this code will never make the bullets fly.
First off, you can set x and y of the new bullet directly (replace everything after "orientate this bullet from players body" with this):
tmpBulletId.x = Object(root).localSurvivor.x;
tmpBulletId.y = Object(root).localSurvivor.y;
Perhaps this already helps, but your code there should already do the same.
But to let these bullets fly into any direction, you also need to add an event listener, like so:
tmpBulletId.addEventListener(Event.ENTER_FRAME, moveBullet);
function moveBullet(e:Event) {
var movedBullet:MovieClip = MovieClip(e.currentTarget);
if (movedBullet.x < 0 || movedBullet.x > movedBullet.stage.width ||
movedBullet.y < 0 || movedBullet.y > movedBullet.stage.height) {
// remove move listener, because the bullet moved out of stage
movedBullet.removeEventListener(Event.ENTER_FRAME);
}
// remove the comment (the //) from the line that you need
MovieClip(e.currentTarget).x += 1; // move right
// MovieClip(e.currentTarget).y -= 1; // move up
// MovieClip(e.currentTarget).x -= 1; // move left
// MovieClip(e.currentTarget).y += 1; // move down
}
This example lets your bullet fly to the right. If you need it flying into another direction, just comment out the line with the "move right" comment and uncomment one of the other lines.
This is of course a very simple example, but it should get you started.
I hope this helps, and that my answer is not the wrong answer to the question.
As far as I have expirienced it you can have only one copy of MovieClip object added to specific child. Best approach is to use ByteArray for the clip source and instantiate new MovieClip and pass the ByteArray as a source. It have something to do with child/parent relation since a DisplayObject can have only one parent (and a way to detach the object from scene too).
Well i ended up writeing the whole code from scratch for a 3rd time and ran into a similar problem and just for reference to anybody else that comes to a problem thats random as this one i found that problem was likly does to a conversion error somewhere that doesn't necessarily break any compiling rules. Just that i was calling a movieclip and not the class it self.