Trying to find out which out of 6 instances I've clicked? - actionscript-3

In Drug.as I have a button, the listener is in Main and I'm trying to find out
which instance I have clicked so I can pick out the price of the drug and make a purchase.
MAIN.AS
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
package
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
/**
* ...
* #author MindGem
*/
public class Main extends Sprite
{
private var drug:Drug;
private var cash:Cash;
private var drugNames:Array = ["Ganja", "Khat", "Extacy", "Amphetamine", "Dopamine", "Heroin", "Cocaine"];
private var drugPrices:Array = [5, 10, 15, 20, 30, 50, 75];
private var randomDrugPrice:uint;
private var drugCollection:Vector.<Drug>;
public function Main():void
{
drugCollection = new Vector.<Drug>;
for (var i:int = 0; i < drugNames.length; i++)
{
randomDrugPrice = Math.random() * (i*5) + drugPrices[i];
drug = new Drug();
addChild(drug);
drugCollection.push(drug);
drug.setName(drugNames[i]);
drug.setPrice(randomDrugPrice);
drug.x = 0;
drug.y = (i * 24);
drug.buy.addEventListener(MouseEvent.CLICK, BuyDrug);
}
cash = new Cash();
addChild(cash);
cash.x = 100;
cash.y = 200;
}
public function BuyDrug(e:MouseEvent):void
{
//How can I find out the price or id of the clicked instance?
THIS is where I need to find out which instance I've clicked.
Now, I tried Drug/e.currentTarget).getPrice(), I've tried pushing in the instances
inside a vector and picking out that one, nothing works for me.
I can put the listener on the class itself instead of a button but that makes the whole
class clickable and I have textfields in there I don't want effected by this.
What Can I do?
}
}
}
//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
DRUG.AS
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFieldType;
import flash.text.TextFormat;
/**
* ...
* #author MindGem
*/
public class Drug extends Sprite
{
private var drugNameContainer:MovieClip;
private var drugNameText:TextField;
private var drugPriceContainer:MovieClip;
private var drugPriceText:TextField;
private var textDesigner:TextFormat;
private var buyDrugText:TextField;
public var buy:MovieClip;
private var buyLabel:TextField;
private var price:uint = 12;
private var drugName:String = "Cocaine";
public function Drug()
{
buyLabel = new TextField();
drugNameContainer = new MovieClip();
drugPriceContainer = new MovieClip();
buy = new MovieClip();
buyDrugText = new TextField();
textDesigner = new TextFormat();
drugNameText = new TextField();
drugPriceText = new TextField();
textDesigner.align = "right";
textDesigner.font = "_sans";
textDesigner.size = 13;
drugNameContainer.graphics.beginFill(0xeeeeee);
drugNameContainer.graphics.lineStyle(1, 0xbbbbbb);
drugNameContainer.graphics.drawRoundRect(50, 50, 120, 20, 6, 6);
drugPriceContainer.graphics.beginFill(0xeeeeee);
drugPriceContainer.graphics.lineStyle(1, 0xbbbbbb);
drugPriceContainer.graphics.drawRoundRect(175, 50, 50, 20, 6, 6);
buy.graphics.beginFill(0x60ce0f);
buy.graphics.lineStyle(2, 0x000000);
buy.graphics.drawRoundRect(275, 50, 50, 21, 6, 6);
buy.buttonMode = true;
drugPriceText.x = 120;
drugPriceText.y = 51;
drugNameText.x = 66;
drugNameText.y = 50;
buyDrugText.type = TextFieldType.INPUT;
buyDrugText.text = "1";
buyDrugText.x = 230;
buyDrugText.y = 50;
buyDrugText.background = true;
buyDrugText.backgroundColor = 0xcccccc;
buyDrugText.border = true;
buyDrugText.borderColor = 0x000000;
buyDrugText.width = 40;
buyDrugText.height = 20;
buyDrugText.maxChars = 3;
buyDrugText.restrict = "0-9";
buyDrugText.setTextFormat(textDesigner);
buyLabel.text = "BUY";
buyLabel.x = 217;
buyLabel.y = 51;
buyLabel.mouseEnabled = false;
buyLabel.setTextFormat(textDesigner);
addChild(drugNameContainer);
addChild(drugPriceContainer);
addChild(drugNameText);
addChild(buy);
addChild(buyDrugText);
addChild(drugPriceText);
addChild(buyLabel);
}
public function setName(p_drugName:String):void
{
drugName = p_drugName;
drugNameText.text = drugName;
drugNameText.mouseEnabled = false;
drugNameText.setTextFormat(textDesigner);
}
public function setPrice(p_price:uint):void
{
price = p_price;
drugPriceText.text = "$" + price;
drugPriceText.mouseEnabled = false;
drugPriceText.setTextFormat(textDesigner);
}
public function getPrice():uint
{
return uint(buyDrugText.text)*price;
}
}
}
Help?

You add the buy MovieClip directly to Drug, so you can just assume:
public function BuyDrug(e:MouseEvent):void
{
var drugClicked:Drug = e.target.parent as Drug;
// more stuff here
}
(You'd have to have the listener added directly to "buy", of course)

drug = new Drug();
drug.name = "drug"+i;
Now u can recognize which item has been clicked.

Related

AS3 MovieClip click event not working

I'm working on a flash slider using as3 and cannot get the click event to fire which clicked on a MovieClip.
The click event works perfectly when targeting the stage but not any MC.
Below is all the code in the project.
The part in question is toward the bottom of SLIDER.as
canvas.addEventListener(MouseEvent.CLICK, this.canvasClick);
The stage and library are both empty. Thank you in advance.
PS: I'm pretty new to flash.
MAIN.AS
package {
import flash.display.MovieClip;
import flash.events.Event;
public class Main extends MovieClip {
public function Main() {
addEventListener(Event.ADDED_TO_STAGE, init)
}
private function init(e:Event){
var images:Array = new Array("./media/engines/Engines-1.jpg", "./media/engines/Engines-2.jpg", "./media/engines/Engines-3.jpg", "./media/engines/Engines-4.jpg", "./media/engines/Engines-5.jpg", "./media/engines/Engines-6.jpg", "./media/engines/Engines-7.jpg", "./media/engines/Engines-8.jpg", "./media/engines/Engines-9.jpg", "./media/engines/Engines-10.jpg", "./media/engines/Engines-11.jpg", "./media/engines/Engines-12.jpg", "./media/engines/Engines-13.jpg");
var slider:Slider = new Slider(stage, images);
}
}
}
SLIDER.AS
package {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
public class Slider extends MovieClip {
private var images:Array;
private var STAGE:Stage;
private var stageWidth:Number;
private var stageHeight:Number;
private var centerX:Number;
private var centerY:Number;
private var tsHeight:Number = 100;
private var tsPadding:Number = 10;
public function Slider(stageGlobal, imageConfig:Array) {
this.STAGE = stageGlobal;
this.images = imageConfig;
this.stageWidth = this.STAGE.stageWidth;
this.stageHeight = this.STAGE.stageHeight;
this.centerX = this.stageWidth / 2;
this.centerY = this.stageHeight / 2;
this.createCanvas();
}
public function createCanvas():void {
// SLIDER HOLDER
var canvas:MovieClip = new MovieClip();
canvas.graphics.drawRoundRect(0, 0, this.stageWidth, this.stageHeight, 15, 15);
canvas.opaqueBackground = 0xDDDDDD;
canvas.mouseEnabled = true;
this.STAGE.addChild(canvas);
// HEADER / TITLE HOLDER
var header:MovieClip = new MovieClip();
header.graphics.drawRoundRect(0, 0, this.stageWidth, 40, 15, 15);
header.opaqueBackground = 0x000000;
canvas.addChild(header);
// FOOTER ACTION HOLDER
var footer:MovieClip = new MovieClip();
footer.graphics.drawRoundRect(0, this.stageHeight - 40, this.stageWidth, 40, 15, 15);
footer.opaqueBackground = 0x000000;
canvas.addChild(footer);
// THUMBSTRIP HOLDER
var thumbstrip:MovieClip = new MovieClip();
thumbstrip.graphics.drawRoundRect(0, this.stageHeight - 160, this.stageWidth, 120, 15, 15);
thumbstrip.opaqueBackground = 0x555555;
canvas.addChild(thumbstrip);
canvas.addEventListener(MouseEvent.CLICK, this.canvasClick);
}
private function canvasClick(e:MouseEvent):void {
trace(e);
}
}
}
It probably has to do with the way you're drawing your MovieClips.
From the docs: "The opaque background region does not respond to mouse events."
Try drawing rectangles like this:
// SLIDER HOLDER
var canvas:MovieClip = new MovieClip();
canvas.graphics.beginFill(0xDDDDDD);
canvas.graphics.drawRoundRect(0, 0, this.stageWidth, this.stageHeight, 15, 15);
canvas.graphics.endFill();
canvas.mouseEnabled = true;
this.STAGE.addChild(canvas);
You need to add Event after slider added to stage so in the slider class you need to write
package {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
public class Slider extends MovieClip {
private var images:Array;
private var STAGE:Stage;
private var stageWidth:Number;
private var stageHeight:Number;
private var centerX:Number;
private var centerY:Number;
private var tsHeight:Number = 100;
private var tsPadding:Number = 10;
public function Slider(stageGlobal, imageConfig:Array) {
this.STAGE = stageGlobal;
this.images = imageConfig;
this.addEventListener(Event.ADDED_TO_STAGE, added);
}
public function added(e:Event)
{
this.stageWidth = this.STAGE.stageWidth;
this.stageHeight = this.STAGE.stageHeight;
this.centerX = this.stageWidth / 2;
this.centerY = this.stageHeight / 2;
this.createCanvas();
}
public function createCanvas():void {
// SLIDER HOLDER
var canvas:MovieClip = new MovieClip();
canvas.graphics.drawRoundRect(0, 0, this.stageWidth, this.stageHeight, 15, 15);
canvas.opaqueBackground = 0xDDDDDD;
canvas.mouseEnabled = true;
this.STAGE.addChild(canvas);
// HEADER / TITLE HOLDER
var header:MovieClip = new MovieClip();
header.graphics.drawRoundRect(0, 0, this.stageWidth, 40, 15, 15);
header.opaqueBackground = 0x000000;
canvas.addChild(header);
// FOOTER ACTION HOLDER
var footer:MovieClip = new MovieClip();
footer.graphics.drawRoundRect(0, this.stageHeight - 40, this.stageWidth, 40, 15, 15);
footer.opaqueBackground = 0x000000;
canvas.addChild(footer);
// THUMBSTRIP HOLDER
var thumbstrip:MovieClip = new MovieClip();
thumbstrip.graphics.drawRoundRect(0, this.stageHeight - 160, this.stageWidth, 120, 15, 15);
thumbstrip.opaqueBackground = 0x555555;
canvas.addChild(thumbstrip);
canvas.addEventListener(MouseEvent.CLICK, canvasClick);
}
private function canvasClick(e:MouseEvent):void {
trace(e);
}
}
}
I hope it would help :)

ActionScript 3 Apparently I cannot access movieclip

I've created a zoom function but when I try to scale the bg_image nothing happends. It is like I cannot access it's properties. Does anyone know why? :)
Ty!
Main class
package
{
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.text.TextField;
import fl.controls.Button;
import fl.controls.List;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.Event;
import flash.display.Shape;
import fl.transitions.Fly;
import fl.motion.MatrixTransformer;
import flash.events.KeyboardEvent;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.ui.Mouse;
public class Main extends Sprite
{
// Zoom
public static var scale:Number = 1;
public var spImage:Sprite;
public var mat:Matrix;
public var mcIn:MovieClip;
public var mcOut:MovieClip;
public var boardWidth:int = 980;
public var boardHeight:int = 661;
public var boardMask:Shape;
public var externalCenter:Point;
public var internalCenter:Point;
public const scaleFactor:Number = 0.8;
public var minScale:Number = 0.25;
public var maxScale:Number = 10.0;
// ------------------------
// Grafikk
public var bg_image:Sprite;
//-------------------------------
//-----------------------------------------------
public var routeArray:Array;
public var startList:List = new List();
public var sluttList:List = new List();
public var S_Norway:Dictionary = new Dictionary();
public var S_Australia:Dictionary = new Dictionary();
public var S_China:Dictionary = new Dictionary();
public var S_South_Africa:Dictionary = new Dictionary();
public var S_Brazil:Dictionary = new Dictionary();
public var S_USA:Dictionary = new Dictionary();
public var S_France:Dictionary = new Dictionary();
// ------------------------------------------------------
public static var airportDict:Dictionary = new Dictionary();
public function Main()
{
addEventListener(Event.ADDED_TO_STAGE, init);
// ---------------------------------
}
public function init(e:Event):void
{
bg_image = new Image(0, 0);
this.addChild(bg_image);
bg_image.addEventListener(MouseEvent.CLICK, mouseCoordinates);
removeEventListener(Event.ADDED_TO_STAGE, init);
// Zoom
this.graphics.beginFill(0xB6DCF4);
this.graphics.drawRect(0,0,boardWidth,boardHeight);
this.graphics.endFill();
spImage = new Sprite();
this.addChild(spImage);
boardMask = new Shape();
boardMask.graphics.beginFill(0xDDDDDD);
boardMask.graphics.drawRect(0,0,boardWidth,boardHeight);
boardMask.graphics.endFill();
boardMask.x = 0;
boardMask.y = 0;
this.addChild(boardMask);
spImage.mask = boardMask;
minScale = boardWidth / bg_image.width;
mcIn = new InCursorClip();
mcOut = new OutCursorClip();
bg_image.addChild(mcIn);
bg_image.addChild(mcOut);
bg_image.scaleX = minScale;
bg_image.scaleY = minScale;
spImage.addChild(bg_image);
spImage.addChild(mcIn);
spImage.addChild(mcOut);
spImage.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
spImage.addEventListener(MouseEvent.CLICK, zoom);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
S_USA["x"] = 180.7;
S_USA["y"] = 149.9;
S_USA["bynavn"] = "New York";
S_Norway["x"] = 423.7;
S_Norway["y"] = 76.4;
S_Norway["bynavn"] = "Oslo";
S_South_Africa["x"] = -26;
S_South_Africa["y"] = 146;
S_South_Africa["bynavn"] = "Cape Town";
S_Brazil["x"] = 226;
S_Brazil["y"] = 431.95;
S_Brazil["bynavn"] = "Rio de Janeiro";
S_France["x"] = 459.1;
S_France["y"] = 403.9;
S_France["bynavn"] = "Paris";
S_China["x"] = 716.2;
S_China["y"] = 143.3;
S_China["bynavn"] = "Beijing";
S_Australia["x"] = 809.35;
S_Australia["y"] = 414.95;
S_Australia["bynavn"] = "Sydney";
// ----------------------------------------------------
airportDict["USA"] = S_USA;
airportDict["Norway"] = S_Norway;
airportDict["South Africa"] = S_South_Africa;
airportDict["Brazil"] = S_Brazil;
airportDict["France"] = S_France;
airportDict["China"] = S_China;
airportDict["Australia"] = S_Australia;
for (var k:Object in airportDict)
{
var value = airportDict[k];
var key = k;
startList.addItem({label:key, data:key});
sluttList.addItem({label:key, data:key});
var airport:Airport = new Airport(key,airportDict[key]["bynavn"]);
airport.koordinater(airportDict[key]["x"], airportDict[key]["y"]);
bg_image.addChild(airport);
}
// --------------------------------------------
// --------------------------------------------
// -----------------------------------------------
}
private function startDragging(mev:MouseEvent):void
{
spImage.startDrag();
}
private function stopDragging(mev:MouseEvent):void
{
spImage.stopDrag();
}
private function zoom(mev:MouseEvent):void
{
if ((!mev.shiftKey)&&(!mev.ctrlKey))
{
return;
}
if ((mev.shiftKey)&&(mev.ctrlKey))
{
return;
}
externalCenter = new Point(spImage.mouseX,spImage.mouseY);
internalCenter = new Point(bg_image.mouseX,bg_image.mouseY);
if (mev.shiftKey)
{
bg_image.scaleX = Math.max(scaleFactor*bg_image.scaleX, minScale);
bg_image.scaleY = Math.max(scaleFactor*bg_image.scaleY, minScale);
}
if (mev.ctrlKey)
{
trace("Minscale: ", maxScale)
trace("Returned: ", 1/scaleFactor*bg_image.scaleY)
bg_image.scaleX = Math.min(1/scaleFactor*bg_image.scaleX, maxScale);
bg_image.scaleY = Math.min(1/scaleFactor*bg_image.scaleY, maxScale);
}
mat = this.transform.matrix.clone();
MatrixTransformer.matchInternalPointWithExternal(mat,internalCenter,externalCenter);
bg_image.transform.matrix = mat;
}
private function keyHandler(ke:KeyboardEvent):void
{
mcIn.x = spImage.mouseX;
mcIn.y = spImage.mouseY;
mcOut.x = spImage.mouseX;
mcOut.y = spImage.mouseY;
mcIn.visible = ke.ctrlKey;
mcOut.visible = ke.shiftKey;
if (ke.ctrlKey || ke.shiftKey)
{
Mouse.hide();
}
else
{
Mouse.show();
}
}
private function reise(evt:MouseEvent):void
{
var new_flight:Flight = new Flight(airportDict[startList.selectedItem.label]["x"],airportDict[startList.selectedItem.label]["y"],airportDict[sluttList.selectedItem.label]["x"],airportDict[sluttList.selectedItem.label]["y"]);
bg_image.addChild(new_flight);
}
private function mouseCoordinates(event: MouseEvent):void
{
// these are the x and y relative to the object
var localMouseX:Number = bg_image.mouseX;
var localMouseY:Number = bg_image.mouseY;
trace("Local coordinates: ", localMouseX, localMouseY);
// these are the x and y relative to the whole stage
var stageMouseX:Number = event.stageX;
var stageMouseY:Number = event.stageY;
trace("Global coordinates: ", stageMouseX, stageMouseY);
}
}
}
Image class:
package {
import flash.display.Sprite;
import flash.display.MovieClip;
public class Image extends Sprite
{
public function Image(y_:Number, x_:Number)
{
this.y = y_
this.x = x_
}
}
}
You don't have minScale declared, neither maxScale.
bg_image should be declared as Sprite, otherwise Compiler Error: Implicit coercion...
`
public var bg_image:Sprite;
As your image is very small, you may want to add your listener to the stage, and not the image, it would be very dificult to click in such a small image.
Also, here is your example working with MOUSE_WHEEL, instead of Click + Ctrl / Shift
stage.addEventListener(MouseEvent.MOUSE_WHEEL, zoom);
private function zoom(mev:MouseEvent):void
{
mev.delta > 0 ?
bg_image.scaleX = bg_image.scaleY = Math.max(scaleFactor * bg_image.scaleX, minScale) :
bg_image.scaleX = bg_image.scaleY = Math.min(1/scaleFactor * bg_image.scaleX, maxScale) ;
}

actionscript 3 new game btn in main menu not working

I have a problem with my game.
When i played level 1 and i return to my main menu, the button new game doesn't work anymore.
Does anyone know what could be the problem?
this is what i have in my main menu as:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import HomeTitel;
import InstBtn;
import NieuwBtn;
public class Hoofdmenu extends MovieClip
{
private var homeTitel:HomeTitel;
private var instBtn:InstBtn;
private var nieuwBtn:NieuwBtn;
private var inst:Instructions;
private var level1:Level1;
public function Hoofdmenu():void
{
placeHomeTitel();
placeInstructionsBtn();
placeNieuwBtn();
}
private function placeHomeTitel():void
{
homeTitel = new HomeTitel();
addChild(homeTitel);
homeTitel.x = 275;
homeTitel.y = 20;
}
private function placeInstBtn():void
{
instBtn = new InstBtn();
addChild(instBtn);
instBtn.x = 275;
instBtn.y = 225;
instBtn.addEventListener(MouseEvent.CLICK, gotoInstructions);
}
private function gotoInstructions(event:MouseEvent)
{
inst = new Instructoins();
addChild(inst);
}
private function placeNewBtn():void
{
newBtn = new NewBtn();
addChild(newBtn);
newBtn.x = 275;
newBtn.y = 175;
newBtn.addEventListener(MouseEvent.CLICK, gotoLevel1);
}
private function gotoLevel1(event:MouseEvent):void
{
level1 = new Level1();
addChild(level1);
}
}
}
this is what i have in my level1 as:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.utils.Timer;
import flash.events.TimerEvent;
import L1Achtergrond;
import L1Titel;
import MenuBtn;
import Sun;
import Min;
import GameOver;
import WellDone;
import VolgLevel;
import HoofdmenuBtn;
import Opnieuw;
public class Level1 extends MovieClip
{
private var back:L1Achtergrond;
private var titel:L1Titel;
private var menu:MenuBtn;
private var sun:Sun;
private var aantalSun:int = 5;
private var counter:int;
private var sunArray:Array = new Array();
private var timer:Timer;
private var min:Min;
private var gameover:GameOver;
private var welldone:WellDone;
private var volglevel:VolgLevel;
private var opn:Opnieuw;
private var hoofdBtn:HoofdmenuBtn;
private var level1:Level1;
private var level2:Level2;
private var hoofdmenu:Hoofdmenu;
public function Level1():void
{
back = new L1Achtergrond();
addChild(back);
placeTitel();
timer = new Timer(3000,1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, startLevel1);
timer.start();
}
private function placeTitel():void
{
titel = new L1Titel();
addChild(titel);
titel.x = 275;
titel.y = 150;
}
private function startLevel1(event:TimerEvent):void
{
for (counter = 0; counter < aantalSun; counter++)
{
sun = new Sun();
sunArray.push(sun);
addChild(sun);
sun.addEventListener(MouseEvent.CLICK, checkSun);
}
min = new Min();
addChild(min);
min.x = 275;
min.y = 30;
min.play();
min.width = 40;
min.height = 20;
timer = new Timer(20000,1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, gameOver);
timer.start();
menu = new MenuBtn();
addChild(menu);
menu.x = 510;
menu.y = 380;
menu.addEventListener(MouseEvent.CLICK, gotoHoofdmenu);
}
private function checkSun(event:MouseEvent):void
{
aantalSun--;
if (aantalSun == 0)
{
wellDone();
timer.stop();
}
}
public function wellDone():void
{
removeChild(menu);
removeChild(min);
welldone = new WellDone();
addChild(welldone);
welldone.x = 275;
welldone.y = 150;
volglevel = new VolgLevel();
addChild(volglevel);
volglevel.x = 300;
volglevel.y = 250;
volglevel.addEventListener(MouseEvent.CLICK, gotoLevel2);
hoofdBtn = new HoofdmenuBtn();
addChild(hoofdBtn);
hoofdBtn.x = 95;
hoofdBtn.y = 250;
hoofdBtn.addEventListener(MouseEvent.CLICK, gotoHoofdmenuW);
}
private function gameOver(event:TimerEvent):void
{
//timer.stop();
removeChild(min);
removeChild(menu);
for (counter = 0; counter < sunArray.length; counter++)
{
removeChild(sunArray[counter]);
}
gameover = new GameOver();
addChild(gameover);
gameover.x = 275;
gameover.y = 150;
opn = new Opnieuw();
addChild(opn);
opn.x = 300;
opn.y = 250;
opn.addEventListener(MouseEvent.CLICK, level1Opn);
hoofdBtn = new HoofdmenuBtn();
addChild(hoofdBtn);
hoofdBtn.x = 95;
hoofdBtn.y = 250;
hoofdBtn.addEventListener(MouseEvent.CLICK, gotoHoofdmenuG);
}
private function level1Opn(event:MouseEvent):void
{
removeChild(gameover);
removeChild(opn);
removeChild(hoofdBtn);
removeChild(back);
level1 = new Level1();
addChild(level1);
}
private function gotoHoofdmenu(event:MouseEvent):void
{
timer.stop();
removeChild(min);
removeChild(menu);
removeChild(back);
for (counter = 0; counter < sunArray.length; counter++)
{
removeChild(sunArray[counter]);
}
}
private function gotoHoofdmenuW(event:MouseEvent):void
{
removeChild(back);
removeChild(welldone);
removeChild(hoofdBtn);
removeChild(volglevel);
}
private function gotoHoofdmenuG(event:MouseEvent):void
{
removeChild(back);
removeChild(gameover);
removeChild(hoofdBtn);
removeChild(opn);
}
private function gotoLevel2(event:MouseEvent):void
{
removeChild(back);
removeChild(volglevel);
removeChild(hoofdBtn);
removeChild(welldone);
level2 = new Level2();
addChild(level2);
}
}
}
I think you should rebuild/redesign the structure of your game.
Now, your code does few strange things:
in your Main class: everytime you call function gotoLevel1 you create a new instance of Level1
in your Level1 class in the function level1Opn you create another instance of 'Level1' and you add it inside Level1 - quite a mess.
This isn't just small code tweak - you should rebuild it quite significantly.
Seems like you never remove level1 from your menu. Even though you remove all children from Level 1, the movieclip will still exist and be on top of your menu.
I would recommend reading though this tutorial, as it will teach you some basic skills about structuring your code, and specific game development features (sound, preloading, saving things in cookies): http://gamedev.michaeljameswilliams.com/2008/09/17/avoider-game-tutorial-1/

Need to know which sprite was clicked

This is my level selector for a game. You can choose level 1-8, I need to know which one was clicked. e.target doesn't give me much besides the name of the object. I need to know either the place in the array or the name of the picture so I know which level to load up.
package
{
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
public class LevelSelector extends Sprite
{
private var posX:int = 50;
private var posY:int = 50;
[Embed(source="../lib/one.png")]
private var lvl1Class:Class;
private var lvl1:Bitmap = new lvl1Class();
[Embed(source="../lib/two.png")]
private var lvl2Class:Class;
private var lvl2:Bitmap = new lvl2Class();
[Embed(source="../lib/three.png")]
private var lvl3Class:Class;
private var lvl3:Bitmap = new lvl3Class();
[Embed(source="../lib/four.png")]
private var lvl4Class:Class;
private var lvl4:Bitmap = new lvl4Class();
[Embed(source="../lib/five.png")]
private var lvl5Class:Class;
private var lvl5:Bitmap = new lvl5Class();
[Embed(source="../lib/six.png")]
private var lvl6Class:Class;
private var lvl6:Bitmap = new lvl6Class();
[Embed(source="../lib/seven.png")]
private var lvl7Class:Class;
private var lvl7:Bitmap = new lvl7Class();
[Embed(source="../lib/eight.png")]
private var lvl8Class:Class;
private var lvl8:Bitmap = new lvl8Class();
private var myArrayBitmaps:Array = new Array;
private var myArraySprites:Array = new Array;
private var yCounter:int = 1;
public function LevelSelector():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
// entry point
myArrayBitmaps.push(false, lvl1, lvl2, lvl3, lvl4, lvl5, lvl6, lvl7, lvl8);
for (var i:int = 1; i < 9; i++)
{
myArrayBitmaps[i].x = posX;
myArrayBitmaps[i].y = posY;
myArrayBitmaps[i].height = 50;
myArrayBitmaps[i].width = 100;
//myArrayBitmaps[i].name = "lvl_" + i + "";
myArraySprites[i] = new Sprite();
myArraySprites[i].addChild(myArrayBitmaps[i]);
myArraySprites[i].x = posX;
myArraySprites[i].y = posY;
//myArraySprites[i].name = "lvl_" + i + "";
stage.addChild(myArraySprites[i]);
myArraySprites[i].addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
removeThis(e, this);
});
posX += 100;
yCounter += 1;
if (yCounter == 5) {
posY += 100;
posX -= 400;
}
}
}
private function removeThis(e:MouseEvent, temp):void
{
//Need to know the number which was passed, 1-8
}
}
}
I would do something like this:
//...
private function init(e:Event = null):void
{
//...
for (var i:int = 1; i < 9; i++)
{
//...
myArraySprites[i] = new Sprite();
myArraySprites[i].addChild(myArrayBitmaps[i]);
//...
stage.addChild(myArraySprites[i]);
myArraySprites[i].addEventListener(MouseEvent.CLICK, removeThis);
}
}
}
private function removeThis(e:MouseEvent):void
{
var clickTarget:int = myArraySprites.indexOf(e.currentTarget);
trace("Clicked sprite (id): " + clickTarget);
}

A problem with DrawRoundRect size

I'm trying to create a custom button with ActionScript 3.0. I'm suing a round rect as background, but I have a problem with it size.
This is my custom button class:
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.display.Shape;
public class customButton extends Sprite
{
private var background:Shape;
public var bgColor:uint;
public var borderColor:uint;
public var borderSize:uint;
public var cornerRadius:uint;
private var label:TextField;
public function customButton(text:String)
{
super();
this.opaqueBackground = 0xFF0000;
background = new Shape();
borderSize = 1;
borderColor = 0x666666;
bgColor = 0xFFCC00;
cornerRadius = 9;
label = new TextField();
label.text = text;
var format:TextFormat = new TextFormat();
format.font = "Verdana";
format.color = 0;
format.size = 38;
format.underline = true;
label.defaultTextFormat = format;
addChild(background);
addChild(label);
buttonMode = true;
mouseChildren = false;
}
public function draw():void
{
background.graphics.lineStyle(borderSize, borderColor);
background.graphics.beginFill(bgColor);
background.graphics.drawRoundRect(0, 0, this.width, this.height cornerRadius);
background.graphics.endFill();
}
}
}
And this is the code used to show the button:
public function Test01()
{
super();
// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
button = new customButton("Button");
button.x = 200;
button.y = 300;
button.width = 200;
button.height = 100;
button.draw();
addChild(button);
}
If I set this size to the button:
button.width = 200;
button.height = 100;
I get the following:
But I set it to button size:
button.width = 40;
button.height = 20;
(This size is the same used in customButton class). I get:
I don't know why when I use a size of (40, 20) I get a smaller rectangle than that size.
Any advice?
it is happening because you are setting the width directly to the Sprite, it changes the size of the sprite no the size of the background you are drawing.
in your customButton class add some code:
private var _width:Number = 10;
private var _height:Number = 10;
override public function get width():Number { return _width; }
override public function set width(value:Number):void
{
_width = value;
draw ();
}
override public function get height():Number { return _height; }
override public function set height(value:Number):void
{
_height = value;
draw ();
}
private function draw():void
{
background.graphics.clear ()
background.graphics.lineStyle(borderSize, borderColor);
background.graphics.beginFill(bgColor);
background.graphics.drawRoundRect(0, 0, _width, _height, cornerRadius);
background.graphics.endFill();
}
with this code you will be able to chnage the background size everytime, and you will not be affecting the other components.
Your roundRect class size has been fixed, so that it was making no changes when u r increasing the width.
Make two public parameters for both width(Bwidth) and height(Bheight) and access it.
like
button.Bwidth = 100;
package
{
import flash.display.Sprite;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.display.Shape;
public class customButton extends Sprite
{
private var background:Shape;
public var bgColor:uint;
public var borderColor:uint;
public var borderSize:uint;
public var cornerRadius:uint;
public var bWidth:Number;
public var bHeight:Number;
private var label:TextField;
public function customButton(text:String, bW:Number, bH:Number)
{
super();
this.bWidth = bW;
this.bHeight = bH;
background = new Shape();
borderSize = 1;
borderColor = 0x666666;
bgColor = 0xFFCC00;
cornerRadius = 9;
label = new TextField();
label.text = text;
var format:TextFormat = new TextFormat();
format.font = "Verdana";
format.color = 0;
format.size = 38;
format.underline = true;
label.defaultTextFormat = format;
addChild(background);
addChild(label);
buttonMode = true;
mouseChildren = false;
background.graphics.lineStyle(borderSize, borderColor);
background.graphics.beginFill(bgColor);
background.graphics.drawRoundRect(0, 0, bWidth, bHeight, cornerRadius);
background.graphics.endFill();
}
}
}
TRy this