Dragging Sprite Array in Actionscript 3 - actionscript-3

My goal is to spawn a circle on the MOUSE_WHEEL event, and move all of them when a dragging occurs, as detected with MOUSE_DOWN and MOUSE_UP. I've done this by adding each Sprite created into an array, and iterating through it when mouse up/down. Note: Node is just an extension of the Sprite type.
However, for some reason, only the most recently drawn Sprite in the array is being moved. Any ideas why?
My Canvas class:
public function Canvas() {
trace("Starting it");
const background:Sprite = new Sprite();
background.graphics.beginFill(0x00000000);
background.graphics.drawRect(0, 0, this.stage.stageWidth, this.stage.stageHeight);
background.graphics.endFill();
addChild(background);
background.addEventListener(MouseEvent.MOUSE_WHEEL, createNode);
background.addEventListener(MouseEvent.MOUSE_DOWN, startObjectMove);
background.addEventListener(MouseEvent.MOUSE_UP, endObjectMove);
mNodeList = new Array();
}
...
}
My startObjectMove and endObjectMove methods:
public function startObjectMove(pEvent:MouseEvent) : void {
trace("Starting drag...");
trace("There are " + mNodeList.length + " in list");
for (var i:int = 0; i < mNodeList.length; i++) {
var node:Node;
node = Node(mNodeList[i]);
node.startMove(pEvent);
}
}
public function endObjectMove(pEvent:MouseEvent) : void {
trace("Ending drag...");
trace("There are " + mNodeList.length + " in list");
for (var i:int = 0; i < mNodeList.length; i++) {
var node:Node;
node = Node(mNodeList[i]);
node.endMove(pEvent);
}
}
The endMove and startMove methods simply call this.startDrag() and this.endDrag().

You can only use startDrag and stopDrag on one object at a time.
You need to listen for mouse down events on the stage itself - when the user clicks, store the initial position of each node (create two public vars/properties in the Node class), and also record where the mouse starts out.
Then, whenever the mouse moves until it's released, work out how far it's moved since mouse down, and add this amount to the initial position of each node to set its position.
You need to do something like this:
var initX:int;//Variables to store the mouse position on click:
var initY:int;
stage.addEventListener(MouseEvent.MOUSE_DOWN):void {
initX = stage.mouseX;//Store the starting mouse position
initY = stage.mouseY;
//Store the node positions:
for(var i:int = 0; i < mNodeList.length; i++){
var node:Node = Node(mNodeList[i]);
node.startX = node.x;
node.startY = node.y;
}
//Listen for mouse move events
stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMove);
}
stage.addEventListener(MouseEvent.MOUSE_UP):void {
//Stop listening for mouse move events
stage.removeEventListener(MouseEvent.MOUSE_MOVE,mouseMove);
}
//MouseMove event handler:
function mouseMove(e:MouseEvent):void{
for(var i:int = 0; i < mNodeList.length; i++){
var node:Node = Node(mNodeList[i]);
// Position each as amount the mouse has moved
// to each node's initial position:
node.x = (stage.mouseX-initX) + node.startX;
node.y = (stage.mouseY-initY) + node.startY;
}
}

Related

Animation code not fired when mouse is out Clip1 but mouse is inside clip 2

Problem:
When I move the mouse cursor out of Clip 1 but is above Clip 2, the MOUSE_OUT of Clip 1 does not work.
Expectation:
Granted that the mouse is inside Clip 2, the location of the mouse is outside of Clip 1 already, so the function mouse_out() of Clip 1 should fire the code inside it.
Full code:
I am attaching the full code so far.
import flash.display.MovieClip;
cat1.addEventListener(MouseEvent.MOUSE_OVER,mouse_over);
cat1.addEventListener(MouseEvent.MOUSE_OUT,mouse_out);
cat2.addEventListener(MouseEvent.MOUSE_OVER,mouse_over);
cat2.addEventListener(MouseEvent.MOUSE_OUT,mouse_out);
cat3.addEventListener(MouseEvent.MOUSE_OVER,mouse_over);
cat3.addEventListener(MouseEvent.MOUSE_OUT,mouse_out);
cat4.addEventListener(MouseEvent.MOUSE_OVER,mouse_over);
cat4.addEventListener(MouseEvent.MOUSE_OUT,mouse_out);
cat5.addEventListener(MouseEvent.MOUSE_OVER,mouse_over);
cat5.addEventListener(MouseEvent.MOUSE_OUT,mouse_out);
function mouse_over(e:MouseEvent)
{
squareEaseOut(e.currentTarget,["scaleX",1.5,"scaleY",1.5]);
}
function mouse_out(e:MouseEvent)
{
squareEaseOut(e.currentTarget,["scaleX",1,"scaleY",1]);
}
var iSquareEasingInterval:int;
//simple square easing, this can capture several properties to be animated
function squareEaseOut(mc:Object,vars:Array)
{
var checker:int = 0;
clearInterval(iSquareEasingInterval);
var ini:Array = new Array();
var accelNum:Number = 0;
var jerkNum:Number = 0;
var varsLength:uint = vars.length / 2;
for (var i:uint = 0; i<varsLength; i++)
{
ini[i] = mc[vars[2 * i]];
}
function animateEasing()
{
checker++;
if (compare(mc[vars[0]]+(0.25 * (vars[1] - ini[0])) / ((1 + accelNum) * (1 + accelNum)),vars[1]))
{
var end = new Date();
trace("Time lapse: "+(end - startD));
clearInterval(iSquareEasingInterval);
accelNum = 0;
jerkNum = 0;
for (var j:uint = 0; j<varsLength; j++)
{
mc[vars[2 * j]] = vars[(2 * j) + 1];
}
return;
}
for (var k:uint = 0; k<varsLength; k++)
{
mc[vars[2*k]] += (0.26 * (vars[(2*k)+1] - ini[k])) / ((1 + accelNum) * (1 + accelNum));
}
accelNum += 0.150+(jerkNum*jerkNum*jerkNum);
jerkNum += 0.09;
}
function compare(a:Number,b:Number)
{
if (vars[1]>ini[0])
{
return a>b;
}
else if (vars[1]<ini[0])
{
return a<b;
}
}
var startD = new Date();
iSquareEasingInterval = setInterval(animateEasing,20);
};
The problem is that you are calling the same method squareEaseOut when any mouse over or mouse out event occurs. Since you are moving your mouse immediately out of one Movie Clip and on to the other, the same method gets called twice, first for the mouse out (for the old movie clip) and then for the mouse over of the new Movie Clip. This will not result in correct behavior as the second call will override the first one as you are using setInterval and clearing the interval as well on every call.
While there may be multiple ways to solve this, easiest way would be to have separate methods for mouse out and mouse over, although that might lead to some code repetition. Or, you could wait for the first animation to finish and then call the other one.
You can also look at various tweening libraries available to achieve what you want, but thats not something that I would advertise here.
Hope this helps.

Action Script 3: Adding an gotoAndStop Animation

So the other day I found a tutorial on how to create a pattern lock screen in action script. To do so I had to create a class, I have a good grasp on how the class is working. But I want to add an animation so when the user goes over the dots in the pattern and animation plays. But I have no idea how to do something like this through the class. Here is the code I used in my class.
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import fl.transitions.Tween;
import fl.transitions.easing.Strong;
public class Main extends Sprite
{
private var dots:Array = []; // Stores the in stage movieclips
private var pattern:Array = []; //The pattern entered by the user
private var pass:Array = [1,4,7,8,5,2,5]; //The correct pattern to proceed
public function Main():void
{
dots = [one,two,three,four,five,six,seven,eight,nine]; //add the clips in stage
addListeners();
}
private function addListeners():void //adds the listeners to each dot
{
var dotsLength:int = dots.length;
for (var i:int = 0; i < dotsLength; i++)
{
dots[i].addEventListener(MouseEvent.MOUSE_DOWN, initiatePattern);
dots[i].addEventListener(MouseEvent.MOUSE_UP, stopPattern);
}
}
/* Adds a mouse over listener and uses it to add the number of the dot to the pattern */
private function initiatePattern(e:MouseEvent):void
{
var dotsLength:int = dots.length;
for (var i:int = 0; i < dotsLength; i++)
{
dots[i].addEventListener(MouseEvent.MOUSE_OVER, addPattern);
}
pattern.push(dots.indexOf(e.target) + 1); //adds the array index number of the clip plus one, because arrays are 0 based
}
private function addPattern(e:MouseEvent):void
{
pattern.push(dots.indexOf(e.target) + 1); //adds the pattern on mouse over
}
private function stopPattern(e:MouseEvent):void //stops storing the pattern on mouse up
{
var dotsLength:int = dots.length;
for (var i:int = 0; i < dotsLength; i++)
{
dots[i].removeEventListener(MouseEvent.MOUSE_OVER, addPattern);
}
checkPattern();
}
private function checkPattern():void //compares the patterns
{
var pLength:int = pass.length;
var correct:int = 0;
for (var i:int = 0; i < pLength; i++) //compares each number entered in the user array to the pass array
{
if (pass[i] == pattern[i])
{
correct++;
}
}
if (correct == pLength) //if the arrays match
{
//Hides Sign In
MovieClip(root).LockScreen.visible = false;
MovieClip(root).RTID.visible = false;
MovieClip(root).SignIn.visible = false;
//Turns On Main Menu
MovieClip(root).gamemenu_mc.visible = true;
MovieClip(root).biggamesmenu_mc.visible = true;
MovieClip(root).totaltextmenu_mc.visible = true;
MovieClip(root).tmenu_mc.visible = true;
MovieClip(root).smenu_mc.visible = true;
MovieClip(root).optionsmenu_mc.visible = true;
}
pattern = []; //clears the user array
}
}
}
Easiest way I can think to do this is:
inside your dot movie clip, put a stop() action on the first frame
create your animation on the dot timeline and on the last frame of the animation put another stop().
In your mouse over function, tell the dot to play.
private function addPattern(e:MouseEvent):void
{
var dot:MovieClip = MovieClip(e.currentTarget);
if(dot.currentFrame < 2) dot.play(); //play only if on the first frame
pattern.push(dots.indexOf(dot) + 1); //adds the pattern on mouse over
}
Reset the dots animation
private function stopPattern(e:MouseEvent):void //stops storing the pattern on mouse up
{
for (var i:int = 0; i < dots.length; i++)
{
dots[i].removeEventListener(MouseEvent.MOUSE_OVER, addPattern);
dots[i].gotoAndStop(1); //go back to the first frame
}
checkPattern();
}
Alternatively, if you're just want something simple like a layer of the dot fading in/out or the size of the dot increasing, you could just use a tweening library and tween the appropriate property on mouse over.
If you wanted to draw lines to connect the dots, you could do this:
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import fl.transitions.Tween;
import fl.transitions.easing.Strong;
import flash.display.Shape;
public class Main extends Sprite
{
private var lineContainer:Shape = new Shape();
private var dots:Array = []; // Stores the in stage movieclips
private var pattern:Array = []; //The pattern entered by the user //don't make life hard, just store the object itself instead of the index
private var pass:Array;
public function Main():void
{
dots = [one,two,three,four,five,six,seven,eight,nine]; //add the clips in stage
pass = [one,four,seven,eight,five,two,five]; //The correct pattern to proceed
addChildAt(lineContainer, this.getChildIndex(one)); //the line container right behind the first dot.
addListeners();
}
private function addListeners():void //adds the listeners to each dot
{
var dotsLength:int = dots.length;
for (var i:int = 0; i < dotsLength; i++)
{
dots[i].addEventListener(MouseEvent.MOUSE_DOWN, initiatePattern);
dots[i].addEventListener(MouseEvent.MOUSE_UP, stopPattern); //you could attach this to `this` instead of each dot, same result
}
}
/* Adds a mouse over listener and uses it to add the number of the dot to the pattern */
private function initiatePattern(e:MouseEvent):void
{
pattern = []; //reset array
lineContainer.graphics.clear(); //clear lines
for (var i:int = 0; i < dots.length; i++)
{
dots[i].addEventListener(MouseEvent.MOUSE_OVER, addPattern);
}
addPattern(e); //trigger the mouse over for this element
}
private function addPattern(e:MouseEvent):void
{
//if (pattern.indexOf(e.currentTarget) == -1) { //wrap in this if statemnt if only wanted a dot to be selected once (like Android)
pattern.push(e.currentTarget); //adds the pattern on mouse over
drawLines();
var dot:MovieClip = MovieClip(e.currentTarget);
if(dot.currentFrame < 2) dot.play(); //play only if on the first frame
//}
}
private function drawLines():void {
lineContainer.graphics.clear(); //clear the current lines
lineContainer.graphics.lineStyle(5, 0xFF0000); //thickness (5px) and color (red) of the lines
if (pattern.length > 1) { //don't draw if there aren't at least two dots in the pattern
lineContainer.graphics.moveTo(pattern[0].x + pattern[0].width * .5, pattern[0].y + pattern[0].height * .5); //move to first
for (var i:int = 1; i < pattern.length; i++) {
lineContainer.graphics.lineTo(pattern[i].x + pattern[i].width * .5, pattern[i].y + pattern[i].height * .5); //draw a line to the current dot
}
}
lineContainer.graphics.endFill();
}
private function stopPattern(e:MouseEvent):void //stops storing the pattern on mouse up
{
for (var i:int = 0; i < dots.length; i++)
{
dots[i].removeEventListener(MouseEvent.MOUSE_OVER, addPattern);
dots[i].gotoAndStop(1); //go back to the first frame
}
checkPattern();
}
private function checkPattern():void //compares the patterns
{
var pLength:int = pass.length;
var correct:int = 0;
for (var i:int = 0; i < pLength; i++) //compares each number entered in the user array to the pass array
{
if (pass[i] == pattern[i])
{
correct++;
}
}
if (correct == pLength) //if the arrays match
{
//Hides Sign In
MovieClip(root).LockScreen.visible = false;
MovieClip(root).RTID.visible = false;
MovieClip(root).SignIn.visible = false;
//Turns On Main Menu
MovieClip(root).gamemenu_mc.visible = true;
MovieClip(root).biggamesmenu_mc.visible = true;
MovieClip(root).totaltextmenu_mc.visible = true;
MovieClip(root).tmenu_mc.visible = true;
MovieClip(root).smenu_mc.visible = true;
MovieClip(root).optionsmenu_mc.visible = true;
}
pattern = []; //clears the user array
lineContainer.graphics.clear(); //clear the lines
}
}
}

Multiple sprites added in loop, but only last sprite clickable

I have multiple bitmap images added into sprites(each image added into 1 sprite) in a loop, then all the sprites added to 1 _contentHolder(Sprite) then that is added to a viewport.
What the problem is, the multiple sprites that are added inside the loop, everything displays with no problem but only the last sprite added is clickable. None of the sprite added before it is clickable. Wondering what the problem is, they are not overlapping and when i hover the mouse over the top of all the sprites, it turns into the mouse clicker but it just won't click.
Thanks for your time!
My code:
function onImageLoaded(e:Event):void {
loadedArray.push(e.target.content as Bitmap);
for(var i:int = 0; i < loadedArray.length; i++){
var currentY1:int = 200;
var image: Sprite= new Sprite;
e.currentTarget.loader.content.height =200;
e.currentTarget.loader.content.y += currentY1;
image.mouseChildren = true; // ignore children mouseEvents
image.mouseEnabled = true; // enable mouse on the object - normally set to true by default
image.useHandCursor = true; // add hand cursor on mouse over
image.buttonMode = true;
image.addChild(loadedArray[i]);
_contentHolder.addChild(image);
}
newArray.push(image);
var viewport:Viewport = new Viewport();
viewport.y = 0;
viewport.addChild(_contentHolder);
var scroller:TouchScroller = new TouchScroller();
scroller.width = 300;
scroller.height = 265;
scroller.x = 10;
scroller.y = 100;
scroller.viewport = viewport;
addChild(scroller);
image.addEventListener(MouseEvent.CLICK, gotoscene);
}
loadImage();
Edit:
function gotoscene(e: MouseEvent):void{
var index:Number;
index = newArray.indexOf(e.target);
trace(index);
blackBox.graphics.beginFill(0x000000);
blackBox.graphics.drawRect( -1, -1, stage.width, stage.height);
blackBox.alpha = 0.7;
addChild(blackBox);
var originalBitmap : BitmapData = loadedArray[index].bitmapData;
var duplicate:Bitmap = new Bitmap(originalBitmap);
duplicate.width = stage.width;
_contentHolder1.addChild(duplicate);
// Use counter here to only add _contentHolder1 once
//Assuming that `samedata` is a class member (I can't see the rest of your code)
addChild(_contentHolder1);
}
Edit2:
private var image:Array = new Array;
//In the For loop
image[i] = new Sprite();
image[i].addChild(loadedArray[i]);
image[i].addEventListener(MouseEvent.CLICK, gotoscene);
function gotoscene(e:MouseEvent):void{
index = image.indexOf(e.target);
trace(index);
}
You should move image.addEventListener(MouseEvent.CLICK, gotoscene); statement into the loop where you add child sprites. Once you do, the listener will be added to all of the sprites, not just the last one that's currently stored in image variable, and is the only one that responds to your clicks.
for(var i:int = 0; i < loadedArray.length; i++){
var currentY1:int = 200;
var image: Sprite= new Sprite;
e.currentTarget.loader.content.height =200;
e.currentTarget.loader.content.y += currentY1;
image.mouseChildren = true; // ignore children mouseEvents
image.mouseEnabled = true; // enable mouse on the object - normally set to true by default
image.useHandCursor = true; // add hand cursor on mouse over
image.buttonMode = true;
image.addEventListener(MouseEvent.CLICK, gotoscene); // <-- THIS
image.addChild(loadedArray[i]);
_contentHolder.addChild(image);
}
And for all that is holy, learn to indent your code, so that you will be able to visually find the start and end of your loops and see if a certain statement is within the loop or not.
I did work for a few years in AS3 and this was a weird an usual problem. I used to solve it with a function that adds the event to each clip:
function someFunction():void {
for (...) {
var image:Sprite = new Sprite();
addSceneListener(image);
}
}
function addSceneListener(mc:Sprite):void {
mc.addEventListener(MouseEvent.CLICK, gogoscene);
}

Flash remove child from timer

I have 25 objects of movie clip class named drone, and when i click it, after 2 seconds I want the object to disappear. I also have 25 timers named countdown. Here is what i do:
function clickHandler (event:MouseEvent):void{
event.currentTarget.hp--;
if(event.currentTarget.hp <= 0)
{
for(var i:int = 0;i<25;i++)
{
if(event.currentTarget == _drone[i])
{
countdown[i].start(); //start timer
}
}
}
}
Here is my timer:
for(var i:int = 0;i<25;i++)
{
countdown[i] = new Timer(2000);
countdown[i].addEventListener(TimerEvent.TIMER,timerHandler);
}
function timerHandler(e:TimerEvent):void {
//remove the drone I clicked
//I also dont know which drone i'm clicking
}
What should I do in the timerHandler to remove the object I clicked?
You can use Dictionary. Use the timer as key and movielcip as value.
import flash.utils.Dictionary;
var dict:Dictionary = new Dictionary();
function clickHandler (event:MouseEvent):void{
event.currentTarget.hp--;
if(event.currentTarget.hp <= 0)
{
for(var i:int = 0;i<25;i++)
{
if(event.currentTarget == _drone[i])
{
dict[countdown[i]] = _drone[i];//set the target mc here
countdown[i].start(); //start timer
break;
}
}
}
}
function timerHandler(e:TimerEvent):void {
var mc:MovieClip = dict[e.target] as MovieClip;//get the object been clicked
if (mc && mc.parent) {
mc.parent.removeChild(mc);//remove it
}
}
With minimal changes, set up an array to track the drones:
var arrayToRemove:Array = new Array();
and then in the click handler store drones to be removed in there:
arrayToRemove.push(event.currentTarget);
and in the timerHandler just remove the first element of the array:
removeChild(arrayToRemove.shift());
Since every delay is the same the order of the events and removals will be preserved. Although, it would probably be better to generalize the code using the above example and store all drones and timers in an arrays, so you can have any number of them.

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.