Delete the bitmap directly behind newly placed bitmap - AS3 - actionscript-3

Tile-based map maker. I want to click the canvas, it places a tile, change tile, click the canvas and it replace the bitmap that I clicked on. .alpha shows clearly that all I am doing is stacking tiles... which will become a problem when I make a 2d array from it. I imagine that there's a way to make layers that they could sit on, but I haven't been able to find anything about it. Here's the code -
public function DrawATile(e:Event, tileToDraw:Object)
{
if (mouseXind <= 19 && mouseYind <= 14) //Only within the canvas!!
{
var newTile:Bitmap = new Bitmap(tileToDraw.Graphic);
newTile.x = mouseXind*32;
newTile.y = mouseYind*32;
newTile.alpha = .4;
addChild(newTile);
setChildIndex(newTile, this.numChildren-1); //Put this graphic behind the grid.
}
}
I want to delete the tile below the new tile that I place. I place a tile... I place a diferent tile over the old tile, I want the old tile to delete... not just stack tiles.

Sounds like you just need to keep track of the previous tile, then remove it accordingly:
private var curTile:Bitmap; //let's keep a reference to the current tile
public function DrawATile(e:Event, tileToDraw:Object)
{
if (mouseXind <= 19 && mouseYind <= 14) //Only within the canvas!!
{
//if there is a current tile, remove it from the display list
if(curTile){
removeChild(curTile);
}
//create your new one as usual
var newTile:Bitmap = new Bitmap(tileToDraw.Graphic);
newTile.x = mouseXind*32;
newTile.y = mouseYind*32;
newTile.alpha = .4;
addChild(newTile);
setChildIndex(newTile, this.numChildren-1); //Put this graphic behind the grid.
curTile = newTile; //make the current tile the one just created
}
}
EDIT
Based off you comment, this seems more like the solution you're looking for.
Sounds like you just want the tile to go away when clicked.
private var curTile:Bitmap; //let's keep a reference to the current tile
public function DrawATile(e:Event, tileToDraw:Object)
{
if (mouseXind <= 19 && mouseYind <= 14) //Only within the canvas!!
{
var newTile:Bitmap = new Bitmap(tileToDraw.Graphic);
newTile.x = mouseXind*32;
newTile.y = mouseYind*32;
newTile.alpha = .4;
addChild(newTile);
setChildIndex(newTile, this.numChildren-1); //Put this graphic behind the grid.
//add a click listener to delete this tile when clicked
newTile.addEventListener(MouseEvent.CLICK, deleteTile, false, 0 true); //make sure the event listener has a weak listener
}
}
private function deleteTile(e:Event):void {
var tile:Bitmap = e.currentTarget as Bitmap;
if(tile.parent) tile.parent.removeChild(tile);
}

I pushed it all into an array, with placeholder strings for every unoccupied cell. Then I check if the index at my current mouse position is a DisplayObject and remove it if it is, replacing it with the new tile.
public function DrawATile(e:Event, tileToDraw:Object)
{
if (mouseXind <= 19 && mouseYind <= 14) //Only within the canvas!!
{
if(aarray[mouseYind][mouseXind] is DisplayObject)
{
removeChild(aarray[mouseYind][mouseXind]);
}
var newTile:Sprite = new Sprite();
var bmp:Bitmap = new Bitmap(tileToDraw.Graphic);
newTile.addChild(bmp);
newTile.x = mouseXind*32;
newTile.y = mouseYind*32;
addChild(newTile);
aarray[mouseYind][mouseXind] = newTile;
}
}

Related

Easy way to make a lot of buttons share a function? AS3

I am trying to do a simple light-up pegboard in flash. I have finished the general logic for 1 peg but there will be a total of 2,300 pegs and I don't want to have to add an event listener to each movieclip.
Here is my code:
import flash.events.Event;
var my_color:ColorTransform = new ColorTransform();
movieClip_1.addEventListener(MouseEvent.MOUSE_UP, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
if (my_color.color == 0)
{
my_color.color = 0x0000FF;
event.target.transform.colorTransform = my_color;
}
else if (my_color.color == 255)
{
my_color.color = 0x00FF00;
event.target.transform.colorTransform = my_color;
}
else if (my_color.color == 65280)
{
my_color.color = 0xFF0000;
event.target.transform.colorTransform = my_color;
}
else if (my_color.color == 16711680)
{
my_color.color = 0xFFFFFF;
event.target.transform.colorTransform = my_color;
}
else if (my_color.color == 16777215)
{
my_color.color = 0x000000;
event.target.transform.colorTransform = my_color;
}
else
{
trace(my_color.color);
}
}
[
Here are 3 ways to accomplish this:
Put the code on the peg's own timeline. (or make a class file, and attach it to your peg object). This will re-use the same code for each peg instance automatically. Just take the same code you have, but use the this keyword instead of a hard reference to the movie clip:
var my_color:ColorTransform = new ColorTransform();
this.addEventListener(MouseEvent.MOUSE_UP, fl_MouseClickHandler);
function fl_MouseClickHandler(event:MouseEvent):void
{
//.....
Make a container Sprite/MovieClip and have all the pegs be the sole children of it. Then iterate over all the children of that container and attach the listener:
//loop through all children of the container and add an event listener
var i:int = container.numChildren;
while(i--){
container.getChildAt(i).addEventListener(....);
}
This is good because you don't have to give them instance names, which would be quite tedious.
Attach a click listener to a common parent of all pegs, and use the target property of the event to see if the click was on a peg.
Assuming you have right-clicked your peg library object, gone to properties and checked "export for actionscript" and given it the Class name "MyPeg", you could do this:
commonParent.addEventListener(MouseEvent.CLICK, parentClick);
function parentClick(e:Event):void {
if(e.target is MyPeg){
//it's a PEG, do something
}
}
Now, depending on how your peg object is structured, target could also refer to a child of your peg (instead of the peg itself). To avoid this if it's applicable, you can disable mouse input on the children of the peg. So on the first frame of your peg object, you could this: this.mouseChildren = false;
Now, even better (less tedious) would be to instantiate your pegs through code too. So as mentioned earlier, export your peg for actionscript in it's properties, and give it a class name ("MyPeg" for my example). Then something along these lines:
var curRow:int = 0;
var curCol:int = 0;
var totalRows:int = 25;
var totalCols:int = 92;
var startingY:int = 10;
var startingX:int = 10;
var padding:int = 2; //gap between pegs
var curPeg:MyPeg;
while(true){
//create the peg, and add it to the display.
curPeg = new MyPeg();
addChild(curPeg);
//add the click listener to this peg
curPeg.addEventListener(MouseEvent.CLICK, fl_mouseClickHandler);
//assign the position of this peg
curPeg.x = startingX + (curCol * (curPeg.width + padding));
curPeg.y = startingY + (curRow * (curPeg.height + padding));
//increment the column
curCol++;
//check if we've reached the last column in the row
if(curCol >= totalCols - 1){
//yes, so reset the column to 0 and increment the row
curCol = 0;
curRow++;
//break out of the loop if the curRow exceeds or is equal to the total rows var
if(curRow >= totalRows) break;
}
}
This way you could change your grid size simply by modifying the number assigned to totalCols and totalRows - no need to tediously move around 2300 objects in FlashPro.
One way to do it is loop through all the children of the parent of your 2300 pegs.
for (var i:int=0; i<numChildren; i++) {
var clip = getChildAt(i);
if (clip.name.indexOf('movieClip_')==0) {
clip.addEventListener((MouseEvent.MOUSE_UP, fl_MouseClickHandler);
}
}
Another way to do it is to add a handler to the entire parent clip and then in the handler check and see if what was clicked is one of your pegs. But you have to disable mouseChildren on the child clips for that to work.
Note that you may want to look at replacing that big if/then statement with switch/case, which is clearer and more compact in this type of situation.

How to apply drag and drop function to all frames in movie clip? Actionscript3

Each frame contain 1 text field. I apply the code on timeline.
But it only gets applied to the last object, which means that I can only drag and drop the last object. Why?
How can I improve this so that I can drag and drop all objects?
for(var j:uint=0; j<3; j++)
{
var q:Ans = new Ans();
q.stop();
q.x = j * 300+50;// set position
q.y = 500;
var r:uint = Math.floor(Math.random() * q_list.length);
q.qface = q_list[r];// assign face to card
q_list.splice(r,1);// remove face from list;
q.gotoAndStop(q.qface+1);
q.addEventListener(MouseEvent.MOUSE_DOWN, startAnsDrag);
q.addEventListener(MouseEvent.MOUSE_UP, stopAnsDrag);
q.addEventListener(Event.ENTER_FRAME, dragAns);
addChild(q);// show the card
}
//----------------------------drag
// offset between sprite location and click
var clickOffset:Point = null;
// user clicked
function startAnsDrag(event:MouseEvent) :void
{
clickOffset = new Point(event.localX, event.localY);
}
// user released
function stopAnsDrag(event:MouseEvent) :void
{
clickOffset = null;
}
// run every frame
function dragAns(event:Event) :void
{
if (clickOffset != null)
{ // must be dragging
q.x = clickOffset.x+mouseX+135;
q.y = clickOffset.y+mouseY;
}
}
Make a new layer in the timeline just for your drag-and-drop code, which you can remove from your other actionscript. Put the code on the first frame in that layer. Now click on and select the last frame on that layer in which you want the code to be effective (probably the last frame of the MovieClip). Press F5 to draw-out the range of frames which will be affected by the code. Voila!

AS3 - Drag using If statement to Next Scene.

I am making an interactive game - and I have this code so far. Where drop1 is a coin and the user drops it into target1 (box) and once they have done they they are able to watch the video play in the next scene. AS you can see when drop1 (coin) is dropped onto the box the coin then disappears
//Array to hold the target instances, the drop instances,
//and the start positions of the drop instances.
var hitArray:Array = new Array(hitTarget1);
var dropArray:Array = new Array(drop1);
var positionsArray:Array = new Array();
//This adds the mouse down and up listener to the drop instances
//and add the starting x and y positions of the drop instances
//into the 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});
}
//This drags the object that has been selected and moves it
//to the top of the display list. This means you can't drag
//this object underneath anything.
function mdown(e:MouseEvent):void {
e.currentTarget.startDrag();
setChildIndex(MovieClip(e.currentTarget), numChildren - 1);
}
//This stops the dragging of the selected object when the mouse is
//released. If the object is dropped on the corresponding target
//then it get set to the x and y position of the target. Otherwise
//it returns to the original position.
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])) {
target.x = hitArray[dropIndex].x;
target.y = hitArray[dropIndex].y;
drop1.visible = false;
}else{
target.x = positionsArray[dropIndex].xPos;
target.y = positionsArray[dropIndex].yPos;
}
}
NOW... I want the code to know when the user has dropped the coin in the box and IF the user has they can then watch the video but can only watch the video if they drop the coin in box. How can i code this?
please help.
thank you
If you're still struggling you can always try reading the MANUAL..? I suspect this is why you've had no answer so far. Travelling between frames/scenes requires either gotoAndPlay or gotoAndStop. Check: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/display/MovieClip.html#gotoAndPlay()
Look at example two for scene jumping code. Where it says "intro" (frame label) it's okay to just use a number but scenes must have names.. e.g:
mc1.gotoAndPlay("intro", "Scene 12");
or in your case something like below (assuming you have named it as scene_video)
if (target.hitTestObject(hitArray[dropIndex])) {
target.x = hitArray[dropIndex].x;
target.y = hitArray[dropIndex].y;
drop1.visible = false;
gotoAndStop(1, "scene_video"); }
Again I'm assuming your video player is on frame 1 of that scene so stopping there allows users a chance to watch the video player.

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.