stopImmediatePropagation doesn't work for SimpleButton - actionscript-3

I'm trying to cancel the event in this actionscript3 code:
public class Main extends Sprite
{
public function Main()
{
this.addEventListener(Event.ADDED_TO_STAGE, onAddedToStage);
}
protected function onAddedToStage(event:Event):void
{
this.addEventListener(MouseEvent.MOUSE_OVER, onOver, true, int.MAX_VALUE);
var btn:SimpleButton = new SimpleButton(
createBtnState(0x0000FF),
createBtnState(0x00FFFF),
createBtnState(0x00FF00),
createBtnState(0x0000FF));
btn.x = stage.stageWidth - btn.width >> 1;
btn.y = stage.stageHeight - btn.height >> 1;
addChild(btn);
}
private function createBtnState(color:uint):Sprite
{
var s:Sprite = new Sprite();
s.graphics.beginFill(color, 1);
s.graphics.drawRect(0,0,100,20);
s.graphics.endFill();
return s;
}
protected function onOver(event:MouseEvent):void
{
event.stopImmediatePropagation(); //Don't work
}
}
how to cancel the event hover the button?
In this example, the button responds when you hover.

your hover event seem to be added on the Main Not the Button.
Try putting the event listener on the btn you declared.
protected function onAddedToStage(event:Event):void
{
//this.addEventListener(MouseEvent.MOUSE_OVER, onOver, true, int.MAX_VALUE);
var btn:SimpleButton = new SimpleButton(
createBtnState(0x0000FF),
createBtnState(0x00FFFF),
createBtnState(0x00FF00),
createBtnState(0x0000FF));
btn.x = stage.stageWidth - btn.width >> 1;
btn.y = stage.stageHeight - btn.height >> 1;
addChild(btn);
btn.addEventListener(MouseEvent.MOUSE_OVER, onOver, true, int.MAX_VALUE);
}

Related

AS3 Error 1009 when Debugging

I'm trying to create a game over screen for my space ship game, when player's shields reach 0 it goes to game over screen and stop the gameplay. The game over screen is working, but I can't stop the gameplay. I tried to set the Ship to null when player's shields reach 0 but I got error 1009. And all the gameplay objects (Ship, Enemy...) will loaded to the stage when "public function fGameStart(evt: Event): void {" executes, is there a way that I can stop this function from running when game over? Any help is greatly appreciated!
public class Engine extends MovieClip {
private var preloader: ThePreloader;
public function Engine() {
stage.addEventListener("gameSTART", fGameStart);
stage.addEventListener("gameOVER", fGameOver);
}
private var numStars: int = 80;
public static var enemyList: Array = new Array();
private var ourShip: Ship;
public function fGameStart(evt: Event): void {
ourShip = new Ship(stage);
ourShip.x = stage.stageWidth / 2;
ourShip.y = stage.stageHeight / 2;
ourShip.addEventListener("hit", shipHit, false, 0, true);
stage.addChild(ourShip);
for (var i: int = 0; i < numStars; i++) {
stage.addChildAt(new Star(stage), stage.getChildIndex(ourShip));
}
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
function loop(e: Event): void {
if (Math.floor(Math.random() * 20) == 5) {
var enemy: Stinger = new Stinger(stage, ourShip);
enemy.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
enemy.addEventListener("killed", enemyKilled, false, 0, true);
enemyList.push(enemy);
stage.addChild(enemy);
}
else if (Math.floor(Math.random() * 80) == 5) {
var enemy2: Stinger2 = new Stinger2(stage, ourShip);
enemy2.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
enemy2.addEventListener("killed", enemyKilled, false, 0, true);
enemyList.push(enemy2);
stage.addChild(enemy2);
}
}
}
public function fGameOver(e: Event) {
gotoAndStop(4);
ourShip = null;
}
}
There is no point setting the ourShip variable to null. It will not remove the DisplayObject from the stage, or remove it from memory. In fact the very reason you get this error is you setting it to null.
What you need to do is stop the loop function from triggering.
public function fGameOver(e: Event) {
gotoAndStop(4);
//ourShip = null;
stage.removeChild(ourShip);
removeEventListener(Event.ENTER_FRAME, loop);
}
also setting a weak reference for you listener might be a bad idea here
//addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
//why not:
addEventListener(Event.ENTER_FRAME, loop);

AS3 How to call a button from another class?

I'm trying to create a button that when you click on it, the ship fires a laser, but the button isn't working. I mean I didn't get any error when debugging, however it won't allow me to click on the button, but instead it allows me to click on my ship to fire. Any help is greatly appreciated, thanks!
My Fire.as
package control {
import flash.events.Event;
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import flash.events.Event;
import objects.Ship;
public class Fire extends MovieClip {
private var my_x: Number;
private var my_y: Number;
private var ourShip: Ship;
var mouseDown: Boolean;
public function Fire(margin_left: Number, margin_bottom: Number, ourShip_mc: Ship) {
my_x = margin_left;
my_y = margin_bottom;
ourShip = ourShip_mc;
if (stage) {
init();
} else {
addEventListener(Event.ADDED_TO_STAGE, init);
}
}
private function init(e: Event = null): void {
if (hasEventListener(Event.ADDED_TO_STAGE)) {
removeEventListener(Event.ADDED_TO_STAGE, init);
}
this.x = my_x + this.width / 2;
this.y = stage.stageHeight - my_y - this.height / 2;
this.addEventListener(MouseEvent.CLICK, onClick);
}
private function onClick(event: MouseEvent): void {
//EVENT DISPATCHER
dispatchEvent(new Event("eventshoot", true));
trace("Fire clicked");
}
}
}
My Ship.as
package objects {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.ui.Keyboard;
import flash.ui.Mouse;
import flash.utils.Timer;
import flash.display.JointStyle;
import control.Controller;
import control.Joystick;
import control.Fire;
public class Ship extends MovieClip {
var mouseDown: Boolean;
private var stageRef: Stage;
private var key: Controller;
private var speed: Number = 2.5;
private var vx: Number = 0;
private var vy: Number = 0;
private var friction: Number = 0.93;
private var maxspeed: Number = 8;
//fire related variables
private var fireTimer: Timer; //causes delay between fires
private var canFire: Boolean = true; //can you fire a laser
public var move_left: Boolean = false;
public var move_up: Boolean = false;
public var move_right: Boolean = false;
public var move_down: Boolean = false;
public function Ship(stageRef: Stage): void {
this.stageRef = stageRef;
key = new Controller(stageRef);
this.addEventListener(Event.ENTER_FRAME, ShipMove);
stage.addEventListener("eventshoot", firenow);
//setup your fireTimer and attach a listener to it.
fireTimer = new Timer(250, 1);
fireTimer.addEventListener(TimerEvent.TIMER, fireTimerHandler, false, 0, true);
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
private function ShipMove(event: Event): void {
if (move_left)
vx -= speed;
else if (move_right)
vx += speed;
else
vx *= friction;
if (move_up)
vy -= speed;
else if (move_down)
vy += speed;
else
vy *= friction;
}
public function firenow(event: Event) {
fireLaser();
}
public function loop(e: Event): void {
//update position
x += vx;
y += vy;
//speed adjustment
if (vx > maxspeed)
vx = maxspeed;
else if (vx < -maxspeed)
vx = -maxspeed;
if (vy > maxspeed)
vy = maxspeed;
else if (vy < -maxspeed)
vy = -maxspeed;
//ship appearance
rotation = vx;
scaleX = (maxspeed - Math.abs(vx)) / (maxspeed * 4) + 0.75;
//stay inside screen
if (x > stageRef.stageWidth - 30) {
x = stageRef.stageWidth - 30;
vx = -vx;
} else if (x < 30) {
x = 30;
vx = -vx;
}
if (y > stageRef.stageHeight) {
y = stageRef.stageHeight;
vy = -vy;
} else if (y < 0) {
y = 0;
vy = -vy;
}
}
private function fireLaser(): void {
//if canFire is true, fire a laser
//set canFire to false and start our timer
//else do nothing.
if (canFire) {
stageRef.addChild(new LaserGreen(stageRef, x + vx, y - 10));
canFire = false;
fireTimer.start();
}
}
//HANDLERS
private function fireTimerHandler(e: TimerEvent): void {
//Timer ran, fire again.
canFire = true;
}
public function takeHit(): void {
dispatchEvent(new Event("hit"));
}
}
}
Updated, here's the Engine.as, sorry for not replying it to your comment below, the structure is messed up if I do so.
package objects {
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import control.Joystick;
import control.Fire;
public class Engine extends MovieClip {
private var preloader: ThePreloader;
public function Engine() {
preloader = new ThePreloader(474, this.loaderInfo);
stage.addChild(preloader);
preloader.addEventListener("loadComplete", loadAssets);
preloader.addEventListener("preloaderFinished", showSponsors);
stage.addEventListener("gameSTART", fGameStart);
}
private function loadAssets(e: Event): void {
this.play();
}
private function showSponsors(e: Event): void {
stage.removeChild(preloader);
var ps: PrerollSponsors = new PrerollSponsors(stage);
ps.addEventListener("prerollComplete", showMenu);
ps.preroll();
}
private function showMenu(e: Event): void {
new MainMenu(stage).load();
}
public static var enemyList: Array = new Array();
private var ourShip: Ship;
private var joystick: Joystick;
private var fire: Fire;
private var scoreHUD: ScoreHUD;
public function fGameStart(evt: Event): void {
ourShip = new Ship(stage);
ourShip.x = stage.stageWidth / 2;
ourShip.y = stage.stageHeight / 2;
ourShip.addEventListener("hit", shipHit, false, 0, true);
stage.addChild(ourShip);
joystick = new Joystick(120, 70, ourShip);
addChild(joystick);
fire = new Fire(420, 70, ourShip);
addChild(fire);
scoreHUD = new ScoreHUD(stage);
stage.addChild(scoreHUD);
addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
}
private function loop(e: Event): void {
if (Math.floor(Math.random() * 20) == 5) {
var enemy: E1 = new E1(stage, ourShip);
enemy.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
enemy.addEventListener("killed", enemyKilled, false, 0, true);
enemyList.push(enemy);
stage.addChild(enemy);
} else if (Math.floor(Math.random() * 80) == 5) {
var enemy2: E2 = new E2(stage, ourShip);
enemy2.addEventListener(Event.REMOVED_FROM_STAGE, removeEnemy, false, 0, true);
enemy2.addEventListener("killed", enemyKilled, false, 0, true);
enemyList.push(enemy2);
stage.addChild(enemy2);
}
}
private function enemyKilled(e: Event) {
scoreHUD.updateKills(1);
scoreHUD.updateScore(e.currentTarget.points);
}
private function removeEnemy(e: Event) {
enemyList.splice(enemyList.indexOf(e.currentTarget), 1);
}
private function shipHit(e: Event) {
scoreHUD.updateHits(1);
}
}
}
So every time the fire button (Fire.as) is clicked, it dispatched an event "eventshoot", and the ship (Ship.as) pick it up. And when the ship receive it, the ship itself fires a laser, that's the idea. But since there are prerolls, menus...stuff like that will loaded before starting the game, I can't just simply drag the fire button to the stage. The engine will load the ship, fire button, enemy, score... to the stage when game started. And I got a error 1009 when debugging "TypeError: Error #1009: Cannot access a property or method of a null object reference.", it is from:
stage.addEventListener("eventshoot", fire now);
in Ship.as
I understand that I'm getting this error because there is no fire button on stage, so my ship can't pickup the "eventshoot" event, is there a way I can make the ship only pickup that event after making sure the button is loaded to the stage to avoid the error?
While you certainly can create a class for your button, the functionality to make the ship object fire a laser should not be in the button.
Given a Ship class that looks like this:
package
{
import flash.display.MovieClip;
public class Ship extends MovieClip
{
public function fireLaser():void
{
trace("pew pew");
}
}
}
You can instantiate this class and add it to your main timeline with this code:
var ship:Ship = new Ship();
addChild(ship);
If you placed the symbol by hand you do not need to do this and instead only need to give it an instance name of ship.
To make something clickable, add an event listener to it. For example, to make the ship itself clickable:
var ship:Ship = new Ship();
addChild(ship);
ship.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
function onMouseDown(event:MouseEvent):void
{
trace("ship clicked");
}
If you have a button on the main time line with an instance name of fire, you can as easily add the listener to that button:
var ship:Ship = new Ship();
addChild(ship);
// v---this changed
fire.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
function onMouseDown(event:MouseEvent):void
{
trace("fire button clicked");
}
Last but not least, if you want to call a method on an object instead of using trace(), you can do that, too:
var ship:Ship = new Ship();
addChild(ship);
fire.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
function onMouseDown(event:MouseEvent):void
{
ship.fireLaser(); // this changed, laser fired "pew pew"
}
tl, dr;
The button itself shouldn't do anything. If the button did anything with the ship directly, it would have to know the ship. The button shouldn't know the ship. All the button does is say "I got clicked" by dispatching an event, everything else should be handled outside.
You know, just like when you wrote your question here, it's not the entire internet (including me) sitting in the keyboard buttons of your computer listening to your input. All your keyboard buttons did was saying "I got clicked". Everything else got handled outside, by your operating system, browser, etc.

AS3 - CS6 - Incorect number of arguments

I'm trying to compile my 2D game to test it and I'm getting this error: \Main.as, Line 32 1136: Incorrect number of arguments. Expected 2.
Line 32 contains this code var enemy:Enemy = new Enemy(null);
Any help is always appreciated, thanks everyone.
Code associated with the error (I can post the rest if needed):
Main.as
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends MovieClip
{
public var player:Player;
public var enemy:Enemy;
public var bulletList:Array = [];
public var mousePressed:Boolean = false; //keeps track of whether the mouse is currently pressed down
public var delayCounter:int = 0; //this adds delay between the shots
public var delayMax:int = 7; //change this number to shoot more or less rapidly
public var enemies:Array = [];
public function Main():void
{
player = new Player(stage, 320, 240);
stage.addChild(player);
//stage.addEventListener(MouseEvent.CLICK, shootBullet, false, 0, true); //remove this
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler, false, 0, true);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler, false, 0, true);
stage.addEventListener(Event.ENTER_FRAME, loop, false, 0, true);
for(var numBaddies=0; numBaddies<6;numBaddies++){
var enemy:Enemy = new Enemy(null);
enemy.x = numBaddies*50;
enemy.y = numBaddies*50
stage.addChild(enemy);
enemies.push(enemy);
}
}
public function loop(e:Event):void
{
if(mousePressed) // as long as the mouse is pressed...
{
delayCounter++; //increase the delayCounter by 1
if(delayCounter == delayMax) //if it reaches the max...
{
shootBullet(); //shoot a bullet
delayCounter = 0; //reset the delay counter so there is a pause between bullets
}
}
if(bulletList.length > 0)
{
for(var i:int = bulletList.length-1; i >= 0; i--)
{
bulletList[i].loop();
}
}
/*for(var h = 0; h<bulletList.length; ++h)
{
if(bulletList[h].hitTestObject(this)){
trace("player hit by baddie " + h);
}
}*/
for(var u:int=0; u<enemies.length; u++) {
Enemy(enemies[u]).moveTowards(player.x, player.y);
}
}
public function mouseDownHandler(e:MouseEvent):void //add this function
{
mousePressed = true; //set mousePressed to true
}
public function mouseUpHandler(e:MouseEvent):void //add this function
{
mousePressed = false; //reset this to false
}
public function shootBullet():void //delete the "e:MouseEvent" parameter
{
var bullet:Bullet = new Bullet(stage, player.x, player.y, player.rotation, enemies);
bullet.addEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved, false, 0, true);
bulletList.push(bullet);
stage.addChild(bullet);
}
public function bulletRemoved(e:Event):void
{
e.currentTarget.removeEventListener(Event.REMOVED_FROM_STAGE, bulletRemoved);
bulletList.splice(bulletList.indexOf(e.currentTarget),1);
}
}
}
Enemy.as
package {
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
public class Enemy extends MovieClip {
public var bullets:Array;
public var stageRef:Stage;
private var enemyPositionX, enemyPositionY,xDistance,yDistance,myRotation:int;
public function Enemy(stageRef:Stage, bulletList:Array) {
// constructor code
bullets = bulletList;
this.stageRef = stageRef;
}
public function moveTowards(playerX:int, playerY:int){
xDistance = this.x - playerX;
yDistance = this.y - playerY;
myRotation = Math.atan2(yDistance, xDistance);
this.x -= 3 * Math.cos(myRotation);
this.y -= 3 * Math.sin(myRotation);
}
private function removeSelf():void
{
//removeEventListener(Event.ENTER_FRAME, loop);
if (stageRef.contains(this))
stageRef.removeChild(this);
}
}
}
As you said, error is pointing to:
var enemy:Enemy = new Enemy(null);
and Enemy constructor is:
public function Enemy(stageRef:Stage, bulletList:Array){
So you are missing 2nd parameter - bulletList.

Adding object to another sprite layer causes issues

Essentially, the spawning ships appear above the crosshair whereas I want it to be the other way around. I tried adding the crosshair to another layer but then clicking / 'shooting' the ships does nothing. Any ideas?
public class Main extends MovieClip {
public static var backgroundLayer:Sprite = new Sprite();
public static var gameLayer:Sprite = new Sprite();
public static var interfaceLayer:Sprite = new Sprite();
public static var menuLayer:Sprite = new Sprite();
public var mainMenu:menuMain = new menuMain();
public var intro:IntroSound = new IntroSound();
public var soundControl:SoundChannel = new SoundChannel();
public var crosshair:crosshair_mc;
static var enemyArray:Array = [];
private var enemyShipTimer:Timer;
private var enemyShipTimerMed:Timer;
private var enemyShipTimerSmall:Timer;
public function Main()
{
addMenuListeners();
addChild(gameLayer);
addChild(backgroundLayer);
addChild(interfaceLayer);
addChild(menuLayer);
menuLayer.addChild(mainMenu);
interfaceLayer.addChild(howtoPlay);
interfaceLayer.addChild(gameEnd);
interfaceLayer.addChild(gameAbout);
soundControl = intro.play(0, 100);
stage.addEventListener(Event.ENTER_FRAME, update);
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
}
private function update(e:Event):void
{
for each (var enemy:EnemyShip in enemyArray)
{
enemy.update();
if (enemy.dead)
{
enemy.kill();
}
}
}
private function mouseDown(e:MouseEvent):void
{
if (e.target.name) {
switch (e.target.name) {
case "enemy_big":
updateScore(5);
e.target.parent.damage();
break;
case "enemy_medium":
updateScore(10);
e.target.parent.damage();
break;
case "enemy_small":
updateScore(15);
e.target.parent.damage();
break;
}
}
}
function addMenuListeners():void
{
//Code to add event listeners
}
public function startGame(e:Event)
{
removeMenuListeners();
soundControl.stop();
if (howtoPlay.parent == interfaceLayer)
{
interfaceLayer.removeChild(howtoPlay);
}
if (gameAbout.parent == interfaceLayer)
{
interfaceLayer.removeChild(gameAbout);
}
if (gameEnd.parent == interfaceLayer)
{
interfaceLayer.removeChild(gameEnd);
}
if (mainMenu.parent == menuLayer)
{
menuLayer.removeChild(mainMenu);
}
enemyShipTimer = new Timer(2000);
enemyShipTimer.addEventListener("timer", sendEnemy);
enemyShipTimer.start();
enemyShipTimerMed = new Timer(2500);
enemyShipTimerMed.addEventListener("timer", sendEnemyMed);
enemyShipTimerMed.start();
enemyShipTimerSmall = new Timer(2750);
enemyShipTimerSmall.addEventListener("timer", sendEnemySmall);
enemyShipTimerSmall.start();
crosshair = new crosshair_mc();
gameLayer.addChild(crosshair);
crosshair.mouseEnabled = crosshair.mouseChildren = false;
Mouse.hide();
gameLayer.addEventListener(Event.ENTER_FRAME, moveCursor);
resetScore();
}
function spawnEnemy(type:String, speed:Number) {
var enemy = new EnemyShip(type, speed);
enemyArray.push(enemy);
gameLayer.addChild(enemy);
return enemy;
}
function sendEnemy(e:TimerEvent):void
{
Timer(e.currentTarget).delay = (1+Math.random()*2)*1000;
spawnEnemy("big", Math.random() * 5 + 12);
}
function sendEnemyMed(e:TimerEvent):void
{
Timer(e.currentTarget).delay = (1+Math.random()*2)*1000;
spawnEnemy("medium", Math.random() * 7 + 14);
}
function sendEnemySmall(e:TimerEvent):void
{
Timer(e.currentTarget).delay = (1+Math.random()*2)*1000;
spawnEnemy("small", Math.random() * 9 + 16);
}
static function updateScore(points)
{
score += points;
scoreText.text = String(score);
scoreHeader.setTextFormat(scoreFormat);
scoreText.setTextFormat(scoreFormat);
}
static function resetScore()
{
score = 0;
scoreText.text = String(score);
scoreText.setTextFormat(scoreFormat);
}
static function removeEnemy(enemyShip:EnemyShip):void {
enemyArray.splice(enemyArray.indexOf(enemyShip), 1);
gameLayer.removeChild(enemyShip);
}
function moveCursor(event:Event)
{
crosshair.x=mouseX;
crosshair.y=mouseY;
}
}
}
I expect MouseDowns are intercepted by the parent layer. You have employed mouseEnabled=false for crosshair, now you should do that for its parent.
public static var crosshairLayer:Sprite=new Sprite();
public function Main() {
... // initialize everything first
addChild(gameLayer);
addChild(crosshairLayer);
crosshairLayer.mouseEnabled=false;
crosshairLayer.mouseChildren=false;
}
Then you add crosshair to crosshairLayer.

Removing the box on mouse click in as3

I am trying to remove a box that i have created on the screen.I have a box exported as
Box and a ship exported as player, they are both movie clips. this is the code:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends MovieClip {
//playermovevar
private var _player:MovieClip;
private var _playerSpeed:Number=5;
private var _destinationX:int;
private var _destinationY:int;
//boxaddvar
private var boxAmount:Number=0;
private var boxLimit:Number=20;
private var _root:Object;
public function Main() {
createPlayer();
//playermovlisten
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler);
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseHandlerdown);
//boxaddlisten
addEventListener(Event.ENTER_FRAME, eFrame);
_box.addEventListener(MouseEvent.CLICK, boxclick);
}
//playermoving
private function createPlayer():void {
_destinationX=stage.stageWidth/2;
_destinationY=stage.stageHeight/2;
_player = new Player();
_player.x=stage.stageWidth/2;
_player.y=stage.stageHeight/2;
stage.addChild(_player);
}
private function enterFrameHandler(event:Event):void {
_player.x += (_destinationX - _player.x) / _playerSpeed;
_player.y += (_destinationY - _player.y) / _playerSpeed;
}
private function mouseHandlerdown(event:MouseEvent):void {
_destinationX=event.stageX;
_destinationY=event.stageY;
addEventListener(MouseEvent.MOUSE_UP, mouseHandlerup);
rotatePlayer();
}
private function mouseHandlerup(event:MouseEvent):void {
}
private function rotatePlayer():void {
var radians:Number=Math.atan2(_destinationY-_player.y,_destinationX-_player.x);
var degrees:Number = radians / (Math.PI / 180) + 90;
_player.rotation=degrees;
}
//boxadding
private function eFrame(event:Event):void {
if (boxAmount<=boxLimit) {
boxAmount++;
var _box:Box=new Box ;
_box.y=Math.random()*stage.stageHeight;
_box.x=Math.random()*stage.stageWidth;
addChild(_box);
} else if (boxAmount >= boxLimit) {
removeEventListener(Event.ENTER_FRAME, eFrame);
} else {
addEventListener(Event.ENTER_FRAME, eFrame);
}
}
function boxclick(event:MouseEvent):void {
removeChild(_box);
}
}
It gives me this error:
1120: Access of undefined property _box. _box.addEventListener(MouseEvent.CLICK, boxclick);
1120: Access of undefined property _box. removeChild(_box);
anyone know whats wrong?
thanks
Not sure what results you're wanting but try this and feel free to ask any questions.
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
public class Main extends MovieClip {
//playermovevar
private var _player:Player;
private var _playerSpeed:Number=5;
private var _destinationX:int;
private var _destinationY:int;
//boxaddvar
private var boxAmount:Number=0;
private var boxLimit:Number=20;
private var _root:Object;
private var _box:Box;
private var arrayOfBoxes:Array = new Array(boxLimit);
public function Main() {
createPlayer();
//playermovlisten
stage.addEventListener(Event.ENTER_FRAME, enterFrameHandler, false, 0, true);
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseHandlerdown, false, 0, true);
//boxaddlisten
addEventListener(Event.ENTER_FRAME, eFrame, false, 0, true);
}
//playermoving
private function createPlayer():void {
_destinationX=stage.stageWidth/2;
_destinationY=stage.stageHeight/2;
_player = new Player();
_player.x=stage.stageWidth/2;
_player.y=stage.stageHeight/2;
stage.addChild(_player);
}
private function enterFrameHandler(event:Event):void {
_player.x += (_destinationX - _player.x) / _playerSpeed;
_player.y += (_destinationY - _player.y) / _playerSpeed;
}
private function mouseHandlerdown(event:MouseEvent):void {
_destinationX=event.stageX;
_destinationY=event.stageY;
addEventListener(MouseEvent.MOUSE_UP, mouseHandlerup, false, 0, true);
rotatePlayer();
}
private function mouseHandlerup(event:MouseEvent):void {
}
private function rotatePlayer():void {
var radians:Number=Math.atan2(_destinationY-_player.y,_destinationX-_player.x);
var degrees:Number = radians / (Math.PI / 180) + 90;
_player.rotation=degrees;
}
//boxadding
private function eFrame(event:Event):void {
if (boxAmount<=boxLimit) {
boxAmount++;
_box =new Box();
_box.y=Math.random()*stage.stageHeight;
_box.x=Math.random()*stage.stageWidth;
_box.addEventListener(MouseEvent.CLICK, boxclick, false, 0, true);
arrayOfBoxes.push(_box);
addChild(_box);
} else if (boxAmount >= boxLimit) {
removeEventListener(Event.ENTER_FRAME, eFrame);
} else {
addEventListener(Event.ENTER_FRAME, eFrame, false, 0, true);
}
}
function boxclick(evt:MouseEvent):void {
removeChild(evt.currentTarget as Box);
}
}
}
You forgot to close the } for the package.
Your _box variable does not exists as global attribute, but you are trying to access it globally.
:)
[edit]
Just remove this line from the top
_box.addEventListener(MouseEvent.CLICK, boxclick);
and put it after
var _box:Box=new Box ;
Then change boxclick function to:
function boxclick(event:MouseEvent):void {
var _box:Box = event.currentTarget as Box; // here is your box again
// make with _box what you want here. Like,
removeChild(_box);
}