Why can't I reset this game? I tried resetting variables etc - actionscript-3

I have this flash game coded with AS3. It works on the first round. When you die, the program will loop it back to the game frame in which a couple or errors occur. One. the dead characters from last round still remain still. Two. The speed doubles everytime. Why????
I create a resetEverything() function to reset all variables, remove Event Listeners and a clear.graphics()
Why doesn't anything work?
Here is my code..
stop();
var leftBorder:verticalwall = new verticalwall(); // defining a variable to hold the left wall
addChild(leftBorder); // adding the left wall to the stage
var rightBorder:verticalwall = new verticalwall(); // defining a variable to hold the left wall
rightBorder.x = 790; // pushing the right wall to the edge of the stage
addChild(rightBorder); // adding the right wall to the stage
var topBorder:horizontalwall = new horizontalwall(); // defining a variable to hold the left wall
addChild(topBorder); // adding the top wall to the stage
var bottomBorder:horizontalwall = new horizontalwall(); // defining a variable to hold the bottom wall
bottomBorder.y = 790; // pushing the bottom wall to the base of the stage
addChild(bottomBorder); // adding the bottom wall to the stage
var P1positions:Array = new Array(); //defining a new variable to hold the poistions of Player 1
var P2positions:Array = new Array(); //defining a new variable to hold the poistions of Player 2
graphics.beginFill( 0x000000 ); // defining a colour for the background
graphics.drawRect( 0, 0, 800, 800); // drawing a rectangle for background
graphics.endFill(); // ending the background creating process
stage.addEventListener(Event.ENTER_FRAME, checkPlayersSpeed);
function checkPlayersSpeed(event:Event)
{
if(P1speed == 0 || P2speed == 0){
P1speed = 0;
P2speed = 0;
gotoAndStop(1, "Conclusion");
}
}
//Player 1
var player1col = "0xFF0000";
var Player1:Shape = new Shape(); //defining a variable for Player 1
Player1.graphics.lineStyle(10,0xffff00); //defining the colour of the style
Player1.graphics.beginFill(0xffff00); //begin filling the shape
Player1.graphics.drawRoundRect(0,0,3,3,360);
Player1.graphics.drawCircle(Player1.x, Player1.x, 2.4) //draw a circle
Player1.graphics.endFill(); //finish the filling process
addChild(Player1); //add player 1 to stage
Player1.x = 250;
Player1.y = 250;
var P1leftPressed:Boolean = false; //boolean to check whether the left key for Player 1 was pressed
var P1rightPressed:Boolean = false; //boolean to check whether the right key for Player 1 was pressed
var P1speed = 3.5; //variable to store the speed of which player 1 moves
var P1Dir = 45; //variable containing the direction in which player 1 moves
var P1position, P2position;
Player1.addEventListener(Event.ENTER_FRAME, P1fl_MoveInP1DirectionOfKey); //adding a listener to the player
stage.addEventListener(KeyboardEvent.KEY_DOWN, P1fl_SetKeyPressed); //listener for a key to be pressed
stage.addEventListener(KeyboardEvent.KEY_UP, P1fl_UnsetKeyPressed); // listener for a key to be released
function P1fl_MoveInP1DirectionOfKey(event:Event) //Moves the player depedning on what key was pressed
{
if(Player1.hitTestObject(leftBorder) || Player1.hitTestObject(rightBorder) || Player1.hitTestObject(topBorder) || Player1.hitTestObject(bottomBorder)){ //checking to see whether Player 1 has hit the wall
P1speed = 0; //stopping Player 1 from moving
Player1.removeEventListener(Event.ENTER_FRAME, P1fl_MoveInP1DirectionOfKey); //adding a listener to the player
stage.removeEventListener(KeyboardEvent.KEY_DOWN, P1fl_SetKeyPressed); //listener for a key to be pressed
stage.removeEventListener(KeyboardEvent.KEY_UP, P1fl_UnsetKeyPressed); // listener for a key to be released
}
if (P1leftPressed)
{
P1Dir -= 0.1; //changes the direction to make Player 1 rotate
}
if (P1rightPressed)
{
P1Dir += 0.1; //changes the direction to make Player 1 rotate
}
P1position = [Player1.x, Player1.y]; //defining a variable for Player 1's constant positions
P1positions.push(P1position); //pushes every position of Player 1 to the array
for (var i = 0; i < P1positions.length - 10; i++) { //a loop that opperates for as long as the array is receiving positions
var P1x = P1positions[i][0]; //saving x positions into array with a unique identifier
var P1y = P1positions[i][1]; //saving y positions into array with a unique identifier
if (distanceBetween(P1x, P1y, Player1.x, Player1.y) < 15) { //checking distance between Player 1 and its trail
P1speed = 0;
}
}
Player1.x += P1speed * Math.cos(P1Dir); //this makes player 1 move forard
Player1.y += P1speed * Math.sin(P1Dir); //this makes player 2 move forward
var P1trail:Shape = new Shape; //defining a variable for player 1's trail
graphics.lineStyle(8, player1col); //setting the format for the trail
graphics.drawCircle(Player1.x, Player1.y, 1.4); //drawing the circles within the trail
addChild(P1trail); //adding the circles to the stage
}
function P1fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
{
P1leftPressed = true; //tells the computer that left has been pressed
break;
}
case Keyboard.RIGHT:
{
P1rightPressed = true; //tells the computer that right has been pressed
break;
}
}
}
function P1fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.LEFT:
{
P1leftPressed = false; //tells the computer that left has been released
break;
}
case Keyboard.RIGHT:
{
P1rightPressed = false; //tells the computer that left has been released
break;
}
}
}
function distanceBetween (x1:Number, y1:Number, x2:Number, y2:Number) { // creating a function
// return d = Math.sqrt(x2 - x1)^2 +(y2 - y1)^2);
var diffX = x2 - x1; // creating variable to tidy up the pythagoras line below
var diffY = y2 - y1; // creating variable to tidy up the pythagoras line below
return Math.sqrt(diffX * diffX + diffY * diffY); // using pythagras theorem
}
// Player 2
var player2col = "0x0066CC";
var Player2:Shape = new Shape(); //defining a variable for Player 1
Player2.graphics.lineStyle(10,0xffff00); //defining the colour of the style
Player2.graphics.beginFill(0xffff00); //begin filling the shape
Player2.graphics.drawRoundRect(0,0,3,3,360);
Player2.graphics.drawCircle(Player2.x, Player2.x, 2.4) //draw a circle
Player2.graphics.endFill(); //finish the filling process
addChild(Player2); //add player 1 to stage
Player2.x = 500;
Player2.y = 500;
var P2leftPressed:Boolean = false;
var P2rightPressed:Boolean = false;
var P2speed = 3.5;
var P2Dir = 180;
Player2.addEventListener(Event.ENTER_FRAME, P2fl_MoveInP1DirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, P2fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, P2fl_UnsetKeyPressed);
function P2fl_MoveInP1DirectionOfKey(event:Event)
{
if(Player2.hitTestObject(leftBorder) || Player2.hitTestObject(rightBorder) || Player2.hitTestObject(topBorder) || Player2.hitTestObject(bottomBorder)){
P2speed = 0;
Player2.removeEventListener(Event.ENTER_FRAME, P2fl_MoveInP1DirectionOfKey);
stage.removeEventListener(KeyboardEvent.KEY_DOWN, P2fl_SetKeyPressed);
stage.removeEventListener(KeyboardEvent.KEY_UP, P2fl_UnsetKeyPressed);
}
if (P2leftPressed)
{
P2Dir -= 0.1;
}
if (P2rightPressed)
{
P2Dir += 0.1;
}
P2position = [Player2.x, Player2.y];
//trace(P2position);
P1positions.push(P2position);
for (var a = 0; a < P1positions.length - 10; a++) {
var P2x = P1positions[a][0];
var P2y = P1positions[a][1];
if (distanceBetween(P2x, P2y, Player2.x, Player2.y) < 15) {
P2speed = 0;
}
}
Player2.x += P2speed * Math.cos(P2Dir);
Player2.y += P2speed * Math.sin(P2Dir);
var P2trail:Shape = new Shape;
graphics.lineStyle(8, player2col);
graphics.drawCircle(Player2.x, Player2.y, 1.4);
addChild(P2trail);
}
function P2fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case event.keyCode = 90:
{
P2leftPressed = true;
break;
}
case event.keyCode = 67:
{
P2rightPressed = true;
break;
}
}
}
function P2fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case event.keyCode=90:
{
P2leftPressed = false;
break;
}
case event.keyCode=67:
{
P2rightPressed = false;
break;
}
}
}
Please help!

Related

How to stop player from walking on walls

I'm building a test avatar chat... thingy in ActionScript3, but I've come across a problem, whenever I click the chatbar to say something, my avatar (which is currently a penguin) walks to it -- how can I prevent this from happening? In other words, how do I build a wall and keep the penguins out?
This is the code I'm using to make my penguin move.
stage.addEventListener(MouseEvent.CLICK, myClickReaction);
// speeds ALONG NYPOTENUSE
var v:Number = 7;
// vector of movement
var dir:int = 100;
// mouse click point
var clickPoint:Point = new Point();
// angle doesn't change metween clicks - so it can be global
var angle:Number;
function myClickReaction (e:MouseEvent):void {
clickPoint = new Point(mouseX, mouseY);
angle = Math.atan2(clickPoint.y - penguin.y, clickPoint.x - penguin.x);
dir = angle >= 0 ? -1 : 1;
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
function onEnterFrame(e:Event):void {
var projectedX:Number = penguin.x + v * Math.cos(angle);
var projectedY:Number = penguin.y + v * Math.sin(angle);
var diff:Number = clickPoint.y - projectedY;
if (diff / Math.abs(diff) == dir) {
penguin.x = clickPoint.x;
penguin.y = clickPoint.y;
removeEventListener(Event.ENTER_FRAME, onEnterFrame);
}
else {
penguin.x = projectedX;
penguin.y = projectedY;
}
}

Having an issue with Flash Actionscript3

Wondering if you guys can help me. I've used online tutorials to create the following.
I am working on a small flash project and I've hit a wall. Basically, I've got 3 scenes. A home page, and 2 games. My home page and one of the games are programmed on the timeline within an actions layer. The third game is applied to a Main.as. The problem is that I want to apply a button called home to the Flappy game, but since I've used the .as file for this code, I'm unsure how to do it.
Basically, my question is "How do I add a button to the "Flappy" Scene? Each time i try to do it and run a test, It's playing the Flappy Game over the Scene 1.
Main.as ("Flappy" Scene3)
package{
import flash.display.MovieClip;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.Event; //used for ENTER_FRAME event
//import flash.events.MouseEvent;
public class Main extends MovieClip{
//These are all of the constants used.
const gravity:Number = 1.5; //gravity of the game. How fast ball falls
const dist_btw_obstacles:Number = 300; //distance between two obstacles
const ob_speed:Number = 8; //speed of the obstacle
const jump_force:Number = 15; //force with which it jumps
//variables
var player:Player = new Player();
var lastob:Obstacle = new Obstacle(); //varible to store the last obstacle in the obstacle array
var obstacles:Array = new Array(); //an array to store all the obstacles
var yspeed:Number = 0; //A variable representing the vertical speed of the bird
var score:Number = 0; //A variable representing the score
public function Main(){
init();
}
function init():void {
//initialize all the variables
player = new Player();
lastob = new Obstacle();
obstacles = new Array();
yspeed = 0;
score = 0;
//add player to center of the stage the stage
player.x = stage.stageWidth/2;
player.y = stage.stageHeight/2;
addChild(player);
//create 3 obstacles ()
createObstacle();
createObstacle();
createObstacle();
//Add EnterFrame EventListeners (which is called every frame) and KeyBoard EventListeners
addEventListener(Event.ENTER_FRAME,onEnterFrameHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, key_up);
}
private function key_up(event:KeyboardEvent){
if(event.keyCode == Keyboard.SPACE){
//If space is pressed then make the bird
yspeed = -jump_force;
}
}
function restart(){
if(contains(player))
removeChild(player);
for(var i:int = 0; i < obstacles.length; ++i){
if(contains(obstacles[i]) && obstacles[i] != null)
removeChild(obstacles[i]);
obstacles[i] = null;
}
obstacles.slice(0);
init();
}
function onEnterFrameHandler(event:Event){
//update player
yspeed += gravity;
player.y += yspeed;
//restart if the player touches the ground
if(player.y + player.height/2 > stage.stageHeight){
restart();
}
//Don't allow the sheep to go above the screen
if(player.y - player.height/2 < 0){
player.y = player.height/2;
}
//update obstacles
for(var i:int = 0;i<obstacles.length;++i){
updateObstacle(i);
}
//display the score
scoretxt.text = String(score);
}
//This functions update the obstacle
function updateObstacle(i:int){
var ob:Obstacle = obstacles[i];
if(ob == null)
return;
ob.x -= ob_speed;
if(ob.x < -ob.width){
//if an obstacle reaches left of the stage then change its position to the back of the last obstacle
changeObstacle(ob);
}
//If the bird hits an obstacle then restart the game
if(ob.hitTestPoint(player.x + player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x + player.width/2,player.y - player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y + player.height/2,true)
|| ob.hitTestPoint(player.x - player.width/2,player.y - player.height/2,true)){
restart();
}
//If the bird got through the obstacle without hitting it then increase the score
if((player.x - player.width/2 > ob.x + ob.width/2) && !ob.covered){
++score;
ob.covered = true;
}
}
//This function changes the position of the obstacle such that it will be the last obstacle and it also randomizes its y position
function changeObstacle(ob:Obstacle){
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
lastob = ob;
ob.covered = false;
}
//this function creates an obstacle
function createObstacle(){
var ob:Obstacle = new Obstacle();
if(lastob.x == 0)
ob.x = 800;
else
ob.x = lastob.x + dist_btw_obstacles;
ob.y = 100+Math.random()*(stage.stageHeight-200);
addChild(ob);
obstacles.push(ob);
lastob = ob;
}
}
}
Here is the code for my main page called "Scenery" (Scene 1) which is in an actions layer of timeline.
stop();
import flash.events.MouseEvent;
sun1.addEventListener(MouseEvent.CLICK,cloudy);
function cloudy (e:MouseEvent){
cloud1.x = cloud1.x + 10;
cloud2.x = cloud2.x - 10;
}
pong_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
function mouseDownHandler(event:MouseEvent):void {
gotoAndStop(1, "SheepyPong");
}
dodge_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler3);
function mouseDownHandler3(event:MouseEvent):void {
gotoAndStop(1, "Flappy");
}
This is my code for a very simple "SheepyPong" (Scene2) game which is linked to from front page:
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var velocityX:Number = 5;
var velocityY:Number = 5;
movieClip_1.addEventListener(Event.ENTER_FRAME, fl_MoveInDirectionOfKey);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function fl_MoveInDirectionOfKey(event:Event)
{
if (upPressed)
{
movieClip_1.y -= 5;
}
if (downPressed)
{
movieClip_1.y += 5;
}
sheep.x += velocityX;
sheep.y += velocityY;
if(sheep.y + sheep.height/2 > stage.stageHeight || sheep.y - sheep.height/2 < 0){
velocityY *= -1
}
if(sheep.hitTestObject(AI) || sheep.hitTestObject(movieClip_1)){
velocityX *= -1;
}
if (sheep.x < 0) {
score2.text = (int(score2.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
if (sheep.x > stage.stageWidth) {
score1.text = (int(score1.text) +1).toString();
sheep.x = 275;
sheep.y = 200;
velocityX *= -1;
}
AI.y = sheep.y;
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = true;
break;
}
case Keyboard.DOWN:
{
downPressed = true;
break;
}
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
switch (event.keyCode)
{
case Keyboard.UP:
{
upPressed = false;
break;
}
case Keyboard.DOWN:
{
downPressed = false;
break;
}
}//end of switch
}//end of function
home_btn.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler1);
function mouseDownHandler1(event:MouseEvent):void {
gotoAndStop(1, "Scenery");
}
I'm also getting this error in output when I run it. It's not actually affecting the outpu
TypeError: Error #1009: Cannot access a property or method of a null object reference.
at Main/onEnterFrameHandler()[/Users/mynamehere/Documents/Game/Main.as:91]
//This is line 91 in the Main.as file:
scoretxt.text = String(score);

Flash CS6 not recognizing functions and packages

I'm working on a 3D game for the Technology Student Association.
I am an amateur programmer, so this is probably why I'm having these problems. It started at first by adding a 3rd level, and Flash not recognizing the packages that the private functions are in. Please advise, here's the code:
package {
import flash.display.*;
import flash.events.*;
import flash.geom.*;
public class Dungeon3D extends MovieClip {
public var viewSprite:Sprite; // everything
public var worldSprite:Sprite; // walls, ceiling, floor, coins
// references to objects
public var map:Map; // mc to use for wall and coin positions
public var map2:Map2; // mc to use for wall and coin positions
public var squares:Array; // blocks on map
public var worldObjects:Array; // walls and coins
private var charPos:Point; // player location
// keyboard input
private var leftArrow, rightArrow, upArrow, downArrow: Boolean;
// car direction and speed
private var dir:Number = 90;
private var speed:Number = 0;
//mrb: variables
private var gameMode:String = "start";
public var playerObjects:Array;
private var gameScore:int;
private var playerLives:int;
// start game
public function startGame() {
gameMode = "play";
playerObjects = new Array();
gameScore = 0;
playerLives = 3;
}
public function startDungeon3D() {
viewSprite = new Sprite();
viewSprite.x = 275;
viewSprite.y = 250;
viewSprite.z = -500;
addChild(viewSprite);
// add an inner sprite to hold everything, lay it down
worldSprite = new Sprite();
viewSprite.addChild(worldSprite);
worldSprite.rotationX = -90;
// cover above with ceiling tiles
for(var i:int=-5;i<5;i++) {
for(var j:int=-6;j<1;j++) {
var ceiling:Ceiling = new Ceiling();
ceiling.x = i*200;
ceiling.y = j*200;
ceiling.z = -200; // above
worldSprite.addChild(ceiling);
}
}
// cover below with floor tiles
for(i=-5;i<5;i++) {
for(j=-6;j<1;j++) {
var floor:Floor = new Floor();
floor.x = i*200;
floor.y = j*200;
floor.z = 0; // below
worldSprite.addChild(floor);
}
}
// get the game map
map = new Map();
// look for squares in map, and put four walls in each spot
// also move coins up and rotate them
worldObjects = new Array();
squares = new Array();
for(i=0;i<map.numChildren;i++) {
var object = map.getChildAt(i);
//var mc = this.gamelevel.getChildAt(i);
if (object is Square) {
// add four walls, one for each edge of square
addWall(object.x+object.width/2, object.y, object.width, 0);
addWall(object.x, object.y+object.height/2, object.height, 90);
addWall(object.x+object.width, object.y+object.height/2, object.height, 90);
addWall(object.x+object.width/2, object.y+object.height, object.width, 0);
// remember squares for collision detection
squares.push(object);
} else if (object is Coin) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
} else if (object is Key) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
} else if (object is Chest) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
} else if (object is Door) {
object.z = 77; // move up
object.rotationX = 90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
}
}
// keep track of virtual position of character
charPos = new Point(0,0);
// arrange all walls and coins for distance
zSort();
// respond to key events
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressedDown);
stage.addEventListener(KeyboardEvent.KEY_UP,keyPressedUp);
// advance game
addEventListener(Event.ENTER_FRAME, moveGame);
}
public function startDungeon3D2() {
// create the world and center it
viewSprite = new Sprite();
viewSprite.x = 275;
viewSprite.y = 250;
viewSprite.z = -500;
addChild(viewSprite);
// add an inner sprite to hold everything, lay it down
worldSprite = new Sprite();
viewSprite.addChild(worldSprite);
worldSprite.rotationX = -90;
// cover above with ceiling tiles
for(var i:int=-5;i<5;i++) {
for(var j:int=-6;j<1;j++) {
var ceiling:Ceiling = new Ceiling();
ceiling.x = i*200;
ceiling.y = j*200;
ceiling.z = -200; // above
worldSprite.addChild(ceiling);
}
}
// cover below with floor tiles
for(i=-5;i<5;i++) {
for(j=-6;j<1;j++) {
var floor:Floor = new Floor();
floor.x = i*200;
floor.y = j*200;
floor.z = 0; // below
worldSprite.addChild(floor);
}
}
// get the game map
map2 = new Map2();
// look for squares in map, and put four walls in each spot
// also move coins up and rotate them
worldObjects = new Array();
squares = new Array();
for(i=0;i<map2.numChildren;i++) {
var object = map2.getChildAt(i);
//var mc = this.gamelevel.getChildAt(i);
if (object is Square) {
// add four walls, one for each edge of square
addWall(object.x+object.width/2, object.y, object.width, 0);
addWall(object.x, object.y+object.height/2, object.height, 90);
addWall(object.x+object.width, object.y+object.height/2, object.height, 90);
addWall(object.x+object.width/2, object.y+object.height, object.width, 0);
// remember squares for collision detection
squares.push(object);
} else if (object is Coin) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
} else if (object is Key) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
} else if (object is Chest) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
} else if (object is Door) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
}
}
public function startDungeon3D3() {
// create the world and center it
viewSprite = new Sprite();
viewSprite.x = 275;
viewSprite.y = 250;
viewSprite.z = -500;
addChild(viewSprite);
// add an inner sprite to hold everything, lay it down
worldSprite = new Sprite();
viewSprite.addChild(worldSprite);
worldSprite.rotationX = -90;
// cover above with ceiling tiles
for(var i:int=-5;i<5;i++) {
for(var j:int=-6;j<1;j++) {
var ceiling:Ceiling = new Ceiling();
ceiling.x = i*200;
ceiling.y = j*200;
ceiling.z = -200; // above
worldSprite.addChild(ceiling);
}
}
// cover below with floor tiles
for(i=-5;i<5;i++) {
for(j=-6;j<1;j++) {
var floor:Floor = new Floor();
floor.x = i*200;
floor.y = j*200;
floor.z = 0; // below
worldSprite.addChild(floor);
}
}
// get the game map
map3 = new Map3();
// cover below with floor tiles
for(i=-5;i<5;i++) {
for(j=-6;j<1;j++) {
var floor:Floor = new Floor();
floor.x = i*200;
floor.y = j*200;
floor.z = 0; // below
worldSprite.addChild(floor);
}
}
// look for squares in map, and put four walls in each spot
// also move coins up and rotate them
worldObjects = new Array();
squares = new Array();
for(i=0;i<map3.numChildren;i++) {
var object = map3.getChildAt(i);
//var mc = this.gamelevel.getChildAt(i);
if (object is Square) {
// add four walls, one for each edge of square
addWall(object.x+object.width/2, object.y, object.width, 0);
addWall(object.x, object.y+object.height/2, object.height, 90);
addWall(object.x+object.width, object.y+object.height/2, object.height, 90);
addWall(object.x+object.width/2, object.y+object.height, object.width, 0);
// remember squares for collision detection
squares.push(object);
} else if (object is Coin) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
} else if (object is Key) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
} else if (object is Chest) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
} else if (object is Door) {
object.z = -50; // move up
object.rotationX = -90; // turn to face player
worldSprite.addChild(object);
worldObjects.push(object); // add to array fo zSort
}
}
// keep track of virtual position of character
charPos = new Point(0,0);
// arrange all walls and coins for distance
zSort();
// respond to key events
stage.addEventListener(KeyboardEvent.KEY_DOWN,keyPressedDown);
stage.addEventListener(KeyboardEvent.KEY_UP,keyPressedUp);
// advance game
addEventListener(Event.ENTER_FRAME, moveGame);
}
// add a vertical wall
public function addWall(x, y, len, rotation) {
var wall:Wall = new Wall();
wall.x = x;
wall.y = y;
wall.z = -wall.height/2;
wall.width = len;
wall.rotationX = 90;
wall.rotationZ = rotation;
worldSprite.addChild(wall);
worldObjects.push(wall);
}
// set arrow variables to true
public function keyPressedDown(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = true;
} else if (event.keyCode == 39) {
rightArrow = true;
} else if (event.keyCode == 38) {
upArrow = true;
} else if (event.keyCode == 40) {
downArrow = true;
}
}
// set arrow variables to false
public function keyPressedUp(event:KeyboardEvent) {
if (event.keyCode == 37) {
leftArrow = false;
} else if (event.keyCode == 39) {
rightArrow = false;
} else if (event.keyCode == 38) {
upArrow = false;
} else if (event.keyCode == 40) {
downArrow = false;
}
}
private function turnPlayer(d) {
// change direction
dir += d;
// rotate world to change view
viewSprite.rotationY = dir-90;
}
// main game function
public function moveGame(e) {
// see if turning left or right
var turn:Number = 0;
if (leftArrow) {
turn = 10;
} else if (rightArrow) {
turn = -10;
}
// turn
if (turn != 0) {
turnPlayer(turn);
}
// if up arrow pressed, then accelerate, otherwise decelerate
speed = 0;
if (upArrow) {
speed = 10;
} else if (downArrow) {
speed = -10;
}
// move
if (speed != 0) {
movePlayer(speed);
}
// re-sort objects
if ((speed != 0) || (turn != 0)) {
zSort();
}
// see if any coins hit
checkCoins();
checkKey();
checkChest();
checkDoor();
}
public function movePlayer(d) {
// calculate current player area
// make a rectangle to approximate space used by player
var charSize:Number = 50; // approximate player size
var charRect:Rectangle = new Rectangle(charPos.x-charSize/2, charPos.y-charSize/2, charSize, charSize);
// get new rectangle for future position of player
var newCharRect:Rectangle = charRect.clone();
var charAngle:Number = (-dir/360)*(2.0*Math.PI);
var dx:Number = d*Math.cos(charAngle);
var dy:Number = d*Math.sin(charAngle);
newCharRect.x += dx;
newCharRect.y += dy;
// calculate new location
var newX:Number = charPos.x + dx;
var newY:Number = charPos.y + dy;
// loop through squares and check collisions
for(var i:int=0;i<squares.length;i++) {
// get block rectangle, see if there is a collision
var blockRect:Rectangle = squares[i].getRect(map);
if (blockRect.intersects(newCharRect)) {
// horizontal push-back
if (charPos.x <= blockRect.left) {
newX += blockRect.left - newCharRect.right;
} else if (charPos.x >= blockRect.right) {
newX += blockRect.right - newCharRect.left;
}
// vertical push-back
if (charPos.y >= blockRect.bottom) {
newY += blockRect.bottom - newCharRect.top;
} else if (charPos.y <= blockRect.top) {
newY += blockRect.top - newCharRect.bottom;
}
}
}
// move character position
charPos.y = newY;
charPos.x = newX;
// move terrain to show proper view
worldSprite.x = -newX;
worldSprite.z = newY;
}
// spin coins and see if any have been hit
private function checkCoins() {
// look at all objects
for(var i:int=worldObjects.length-1;i>=0;i--) {
// only look at coins
if (worldObjects[i] is Coin) {
// spin it!
worldObjects[i].rotationZ += 10;
// check distance from character
var dist:Number = Math.sqrt(Math.pow(charPos.x-worldObjects[i].x,2)+Math.pow(charPos.y-worldObjects[i].y,2));
// if close enough, remove coin
if (dist < 50) {
worldSprite.removeChild(worldObjects[i]);
worldObjects.splice(i,1);
}
}
}
}
// spin coins and see if any have been hit
private function checkKey() {
// look at all objects
for(var i:int=worldObjects.length-1;i>=0;i--) {
// only look at coins
if (worldObjects[i] is Key) {
// spin it!
worldObjects[i].rotationZ += 10;
// check distance from character
var dist:Number = Math.sqrt(Math.pow(charPos.x-worldObjects[i].x,2)+Math.pow(charPos.y-worldObjects[i].y,2));
// if close enough, remove coin
if (dist < 50) {
getObject(i); // mrb: call to getobject
worldSprite.removeChild(worldObjects[i]);
worldObjects.splice(i,1);
}
}
}
}
// spin coins and see if any have been hit
private function checkChest() {
// look at all objects
for(var i:int=worldObjects.length-1;i>=0;i--) {
// only look at coins
if (worldObjects[i] is Chest) {
// spin it!
worldObjects[i].rotationZ += 10;
// check distance from character
var dist:Number = Math.sqrt(Math.pow(charPos.x-worldObjects[i].x,2)+Math.pow(charPos.y-worldObjects[i].y,2));
// if close enough and have the key end the level; don't remove if no key
if (dist < 50) {
getObject(i); // mrb: call to getobject
//worldSprite.removeChild(worldObjects[i]);
//worldObjects.splice(i,1);
}
}
}
}
// spin coins and see if any have been hit
private function checkDoor() {
// look at all objects
for(var i:int=worldObjects.length-1;i>=0;i--) {
// only look at coins
if (worldObjects[i] is Door) {
// spin it!
worldObjects[i].rotationZ += 10;
// check distance from character
var dist:Number = Math.sqrt(Math.pow(charPos.x-worldObjects[i].x,2)+Math.pow(charPos.y-worldObjects[i].y,2));
// if close enough and have the key end the level; don't remove if no key
if (dist < 50) {
getObject(i); // mrb: call to getobject
//worldSprite.removeChild(worldObjects[i]);
//worldObjects.splice(i,1);
}
}
}
}
// player collides with objects
public function getObject(objectNum:int) {
// award points for treasure
if (worldObjects[objectNum] is Treasure) {
//var pb:PointBurst = new PointBurst(map,100,worldObjects[objectNum].x,worldObjects[objectNum].y);
//gamelevel.removeChild(otherObjects[objectNum]);
//otherObjects.splice(objectNum,1);
//addScore(100);
// got the key, add to inventory
} else if (worldObjects[objectNum] is Key) {
//pb = new PointBurst(gamelevel,"Got Key!" ,otherObjects[objectNum].x,otherObjects[objectNum].y);
playerObjects.push("Key");
trace(playerObjects.indexOf("Key"));
//gamelevel.removeChild(otherObjects[objectNum]);
//otherObjects.splice(objectNum,1);
// hit the door, end level if hero has the key
} else if (worldObjects[objectNum] is Door) {
if (playerObjects.indexOf("Key") == -1) return; // i don't have the key
if (worldObjects[objectNum].currentFrame == 1) { // i got the key
worldObjects[objectNum].gotoAndPlay("open");
levelComplete();
}
// got the chest, game won, if hero has the key
} else if (worldObjects[objectNum] is Chest) {
if (playerObjects.indexOf("Key") == -1) return;
trace(worldObjects[objectNum].currentFrame);
if (worldObjects[objectNum].currentFrame == 1) {
worldObjects[objectNum].gotoAndStop("open");
gameComplete();
}
}
}
// level over, bring up dialog
public function levelComplete() {
gameMode = "done";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "Level Complete!";
}
// game over, bring up dialog
public function gameComplete() {
gameMode = "gameover";
var dialog:Dialog = new Dialog();
dialog.x = 175;
dialog.y = 100;
addChild(dialog);
dialog.message.text = "You Got the Treasure!";
}
// dialog button clicked
public function clickDialogButton(event:MouseEvent) {
removeChild(MovieClip(event.currentTarget.parent));
// new life, restart, or go to next level
if (gameMode == "dead") {
// reset hero
//showLives();
//hero.mc.x = hero.startx;
//hero.mc.y = hero.starty;
gameMode = "play";
} else if (gameMode == "gameover") {
cleanUp();
gotoAndStop("start");
} else if (gameMode == "done") {
cleanUp();
nextFrame();
}
// give stage back the keyboard focus
stage.focus = stage;
}
// clean up game
public function cleanUp() {
//removeChild(gamelevel);
//this.removeEventListener(Event.ENTER_FRAME,gameLoop);
//stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyDownFunction);
//stage.removeEventListener(KeyboardEvent.KEY_UP,keyUpFunction);
stage.removeEventListener(KeyboardEvent.KEY_DOWN,keyPressedDown);
stage.removeEventListener(KeyboardEvent.KEY_UP,keyPressedUp);
this.removeEventListener(Event.ENTER_FRAME, moveGame);
removeChild(viewSprite);
}
// sort all objects so the closest ones are highest in the display list
private function zSort() {
var objectDist:Array = new Array();
for(var i:int=0;i<worldObjects.length;i++) {
var z:Number = worldObjects[i].transform.getRelativeMatrix3D(root).position.z;
objectDist.push({z:z,n:i});
}
objectDist.sortOn( "z", Array.NUMERIC | Array.DESCENDING );
for(i=0;i<objectDist.length;i++) {
worldSprite.addChild(worldObjects[objectDist[i].n]);
}
}
}
}
}
These are the errors im getting now, even though the code IS there. The file name IS Dungeon3D.as
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 217 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 324 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 337 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 350 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 362 1013: The private attribute may be used only on class property definitions.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 372 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 412 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 465 1013: The private attribute may be used only on class property definitions.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 484 1013: The private attribute may be used only on class property definitions.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 504 1013: The private attribute may be used only on class property definitions.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 524 1013: The private attribute may be used only on class property definitions.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 545 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 581 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 591 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 601 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 624 1114: The public attribute can only be used inside a package.
C:\Users\school\Desktop\Dungeon3DV3\Dungeon3D.as, Line 637 1013: The private attribute may be used only on class property definitions.
Whenever i change where something is in the code itself, i still get the same errors. Flash screw up? Or is the code being drawn from a different folder?
You missed } after startDungeon3D2() method. Add it in line number 214.

Adding another Movie Clip into another Frame

I am attempting to add a new movie clip into the next frame of my shooter game.
I am using Actionscript 3.0
To give a basis of what I need help with for my assessment. When the score =50, switch to the next frame. And this is where I would like to add a new type of movie clip for the user to shoot!
Here is the code I have so far.
FRAME 1
//Tate's open screen
stop(); //makes the screen wait for events
paraBtn.addEventListener(MouseEvent.CLICK, playClicked); //this line is making your button an mouse click event
function playClicked(evt: MouseEvent): void { // now we are calling the event from this function and telling it to go to the next frame we labelled play
gotoAndStop("frame2");
// All rights of this music goes towards the makers of the game "Risk of Rain" which was made by Hapoo Games
}
FRAME 2 (Where the game actually starts)
stop();
// This plays the sound when left click is used
var spitSound: Sound = new Sound();
spitSound.load(new URLRequest("gunSound.mp3"));
//This plays the gameover sound when your lives reach 0
var overSound: Sound = new Sound();
overSound.load(new URLRequest("Gameover.mp3"));
//This plays the sound when you are hit
var etSound: Sound = new Sound();
etSound.load(new URLRequest("Urgh.mp3"));
//This sets the lives and points.
stage.addEventListener(MouseEvent.MOUSE_MOVE, aimTurret);
var points: Number = 0;
var lives: Number = 3;
var target: MovieClip;
var _health: uint = 100;
initialiseCursor();
//This variable stops the multiple errors with the move objects and bullets and range to stop compiling.
var Gameover: Boolean = false;
//This aims the turrent to where you mouse is on the screen
function aimTurret(evt: Event): void {
if (Gameover == false) {
gun.rotation = getAngle(gun.x, gun.y, mouseX, mouseY);
var distance: Number = getDistance(gun.x, gun.y, mouseX, mouseY);
var adjDistance: Number = distance / 12 - 7;
}
}
function getAngle(x1: Number, y1: Number, x2: Number, y2: Number): Number {
var radians: Number = Math.atan2(y2 - y1, x2 - x1);
return rad2deg(radians);
}
function getDistance(x1: Number, y1: Number, x2: Number, y2: Number): Number {
var dx: Number = x2 - x1;
var dy: Number = y2 - y1;
return Math.sqrt(dx * dx + dy * dy);
}
function rad2deg(rad: Number): Number {
return rad * (180 / Math.PI);
}
//Starts lives and shows text next to the numbers
function initialiseCursor(): void {
Mouse.hide();
target = new Target();
target.x = mouseX;
target.y = mouseY;
target.mouseEnabled = false;
addChild(target);
stage.addEventListener(MouseEvent.MOUSE_MOVE, targetMove);
stage.addEventListener(MouseEvent.MOUSE_DOWN, targetDown);
stage.addEventListener(MouseEvent.MOUSE_UP, targetUp);
livesdisplay.text = String(lives) + " Lives Left";
pointsdisplay.text = String(points) + " Points";
}
function targetMove(evt: MouseEvent): void {
target.x = this.mouseX;
target.y = this.mouseY;
}
function targetDown(evt: MouseEvent): void {
target.gotoAndStop(2);
}
function targetUp(evt: MouseEvent): void {
target.gotoAndStop(1);
}
//Starts bullets and speed of bullets, also addding new arrays for baddies
var gunLength: uint = 90;
var bullets: Array = new Array();
var bulletSpeed: uint = 20;
var baddies: Array = new Array();
stage.addEventListener(MouseEvent.MOUSE_DOWN, fireGun);
function fireGun(evt: MouseEvent) {
if (Gameover == false) {
var bullet: Bullet = new Bullet();
bullet.rotation = gun.rotation;
bullet.x = gun.x + Math.cos(deg2rad(gun.rotation)) * gunLength;
bullet.y = gun.y + Math.sin(deg2rad(gun.rotation)) * gunLength;
addChild(bullet);
bullets.push(bullet);
spitSound.play();
}
}
function deg2rad(deg: Number): Number {
return deg * (Math.PI / 180);
}
stage.addEventListener(Event.ENTER_FRAME, moveObjects);
function moveObjects(evt: Event): void {
if (Gameover == false) {
moveBullets();
moveBaddies();
}
}
function moveBullets(): void {
for (var i: int = 0; i < bullets.length; i++) {
var dx = Math.cos(deg2rad(bullets[i].rotation)) * bulletSpeed;
var dy = Math.sin(deg2rad(bullets[i].rotation)) * bulletSpeed;
bullets[i].x += dx;
bullets[i].y += dy;
if (bullets[i].x < -bullets[i].width || bullets[i].x > stage.stageWidth + bullets[i].width || bullets[i].y < -bullets[i].width || bullets[i].y > stage.stageHeight + bullets[i].width) {
removeChild(bullets[i]);
bullets.splice(i, 1);
}
}
}
// This is the start of the timer
var timer: Timer = new Timer(1000);
timer.addEventListener(TimerEvent.TIMER, addBaddie);
timer.start();
// Adding army men on a timer and only from the top side
function addBaddie(evt: TimerEvent): void {
var baddie: Baddie = new Baddie();
var side: Number = Math.ceil(Math.random() * 1);
if (side == 1) {
baddie.x = Math.random() * stage.stageWidth;
baddie.y = -baddie.height;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = 7;
addChild(baddie);
baddies.push(baddie);
}
function moveBaddies(): void {
for (var i: int = 0; i < baddies.length; i++) {
var dx = Math.cos(deg2rad(baddies[i].angle)) * baddies[i].speed;
var dy = Math.sin(deg2rad(baddies[i].angle)) * baddies[i].speed;
baddies[i].x += dx;
baddies[i].y += dy;
if (baddies[i].hitTestPoint(gun.x, gun.y, true)) {
removeChild(baddies[i]);
baddies.splice(i, 1);
loseLife();
//If baddie was removed then we don’t check for bullet hits
} else {
checkForHit(baddies[i]);
}
}
}
function checkForHit(baddie: Baddie): void {
for (var i: int = 0; i < bullets.length; i++) {
if (baddie.hitTestPoint(bullets[i].x, bullets[i].y, true)) {
removeChild(baddie);
points++;
if (points == 50) {
gotoAndStop("frame3")
}
pointsdisplay.text = String(points) + " Points";
baddies.splice(baddies.indexOf(baddie), 1);
}
}
}
// Keeping track of lost lives and when hitting 0 doing to frame four, also displaying "Lose life!"
function loseLife(): void {
etSound.play();
lives--;
if (lives == 0) {
Gameover = true;
overSound.play();
gotoAndStop("frame4")
}
livesdisplay.text = String(lives) + " Lives Left";
trace("Lose Life!");
}
FRAME 3 (This is where I need help, to add another movie clip) (I have made one for the frame named, "BaddieRed" With the Linkage being "Baddiered"
stop();
// The code from frame2 carries over and works the same in this frame
FRAME 4 (This is the screen where it's gameover)
stop();
timer.stop();
// User need to close by pressing the close button
//And restart the game manually
Is this what you're trying to achieve? Something like...
function addBaddie(evt: TimerEvent): void
{
var baddie : MovieClip;
if (points < 50) { var bad1: Baddie = new Baddie(); baddie = bad1; }
if (points >= 50) { var bad2 : Baddiered = new Baddiered(); baddie = bad2; }
var side: Number = Math.ceil(Math.random() * 1);
if (side == 1)
{
baddie.x = Math.random() * stage.stageWidth;
baddie.y -= baddie.height;
}
baddie.angle = getAngle(baddie.x, baddie.y, gun.x, gun.y);
baddie.speed = 7;
addChild(baddie);
baddies.push(baddie);
}

Mouse_leave cannot make movieclip snap back

I am trying to make a small drag and drop application in flash , i have been able to achieve the following -
1)Drag the movie clips
2)Make sure that two movieclips do not interchange positions when put over each other
3)Make sure the MC that is being dragged stays on top of other movieclips ..
4)Make the movieclip stay when its dropped at designated position
However there is one very important thing i am unable to achieve , when the cursor moves out of stage , the movie clips gets stuck to the cursor , i want that the moment the user goes out of stage the clip that is being dragged goes back to its original position ...
I have tried using the mouse_leave option for this but it does not work...
I am adding the code for drag and drop as below , please guide me here -
Drag Code -
Array to hold the target instances, the drop instances,
and the start positions of the drop instances.
var hitArray:Array = new Array(hitTarget1,hitTarget2,hitTarget3);
var dropArray:Array = new Array(drop1,drop2,drop3);
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);
}
And here is the drop code
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;
}else{
target.x = positionsArray[dropIndex].xPos;
target.y = positionsArray[dropIndex].yPos;
}
}
Please tell me how to use mouse_leave here and make the snap back,
used it in the both drag and drop section like this below
stage.addEventListener(Event.MOUSE_LEAVE, mouseLeave);
but always get some error like stage does not support property x etc. i add some code like equating the x and y but it does not work .. please guide
Jin
MOUSE_LEAVE shows if we are in or out of the stage, but doesn't detect the position of the mouse. You have to collect mouse's data on MOUSE_DOWN, to restrict the instance into the limits.
const LL:uint = 0;
const LT:uint = 0;
const LR:uint = stage.stageWidth;
const LB:uint = stage.stageHeight;
function EnterFrame(e:Event):void {
e.target.x = mouseX;
e.target.y = mouseY;
if (mouseX < LL) {e.target.x = LL;} else if (mouseX > LR) {e.target.x = LR;}
if (mouseY < LT) {e.target.y = LT;} else if (mouseY > LB) {e.target.y = LB;}
}
In your function 'mdown':
e.currentTarget.addEventListener(Event.ENTER_FRAME, EnterFrame);
In your function 'mUp':
target.removeEventListener(Event.ENTER_FRAME, EnterFrame);
General method
Here is the way this can be done. On MOUSE_UP outside the limits, the target is [object stage]. So you have to create a variable __last that will make you recognize the instance (p1 or another) clicked on MOUSE_DOWN. StartDrag() isn't needed:
const LL:uint = 0;
const LT:uint = 0;
const LR:uint = stage.stageWidth;
const LB:uint = stage.stageHeight;
function EnterFrame(e:Event):void {
e.target.x = mouseX;
e.target.y = mouseY;
if (mouseX < LL) {e.target.x = LL;} else if (mouseX > LR) {e.target.x = LR;}
if (mouseY < LT) {e.target.y = LT;} else if (mouseY > LB) {e.target.y = LB;}
}
var __last:*;
p1.addEventListener(MouseEvent.MOUSE_DOWN, OnMouseDown);
function OnMouseDown(e:MouseEvent):void {
__last = MovieClip(e.target);
__last.addEventListener(Event.ENTER_FRAME, EnterFrame);
}
this.stage.addEventListener(MouseEvent.MOUSE_UP, OnMouseUp);
function OnMouseUp(e:MouseEvent):void {
if(__last) __last.removeEventListener(Event.ENTER_FRAME, EnterFrame);
}
To snap it back to original position
const LL:uint = 0;
const LT:uint = 0;
const LR:uint = stage.stageWidth;
const LB:uint = stage.stageHeight;
var __last:*;
var dropIndex:int;
function EnterFrame(e:Event):void {
if (mouseX < LL || mouseX > LR || mouseY < LT || mouseY > LB) {
__last.x = positionsArray[dropIndex].xPos;
__last.y = positionsArray[dropIndex].yPos;
__last.stopDrag();
}
}
var hitArray:Array = new Array(hitTarget1, hitTarget2, hitTarget3);
var dropArray:Array = new Array(drop1, drop2, drop3);
var positionsArray: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});
}
function mdown(e:MouseEvent):void {
__last = e.currentTarget;
dropIndex = dropArray.indexOf(__last);
setChildIndex(MovieClip(__last), numChildren - 1);
__last.startDrag();
addEventListener(Event.ENTER_FRAME, EnterFrame);
}
function mUp(e:MouseEvent):void {
if (__last.hitTestObject(hitArray[dropIndex])) {
__last.x = hitArray[dropIndex].x;
__last.y = hitArray[dropIndex].y;
} else {
__last.x = positionsArray[dropIndex].xPos;
__last.y = positionsArray[dropIndex].yPos;
}
__last.stopDrag();
removeEventListener(Event.ENTER_FRAME, EnterFrame);
}