How to prevent a drag action to affect the childrens of a MovieClip - actionscript-3

My problem is: I have a MovieClip (obj) that users can drag to both sides to navigate, the code I use for this:
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.events.Event;
import flash.geom.Rectangle;
var destination: Point = new Point();
var dragging: Boolean = false;
var speed: Number = 10;
var offset: Point = new Point();
var bounds: Rectangle = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight);
obj.addEventListener(MouseEvent.MOUSE_DOWN, startdrag);
stage.addEventListener(MouseEvent.MOUSE_UP, stopdrag);
obj.addEventListener(Event.ENTER_FRAME, followmouse);
function startdrag(e: MouseEvent): void {
offset.x = obj.mouseX * obj.scaleX;
dragging = true;
}
function stopdrag(e: MouseEvent): void {
dragging = false;
}
function followmouse(e: Event): void {
if (obj) {
if (dragging) {
destination.x = mouseX;
}
obj.x -= (obj.x - (destination.x - offset.x)) / speed;
if (obj.x > bounds.left) {
obj.x = bounds.left;
}
if (obj.x < -obj.width + bounds.right) {
obj.x = -obj.width + bounds.right;
}
}
}
So far so good, the problem comes up when I put some clickable elements inside that MovieClip (obj), here are the code for the clickable elements:
objA.addEventListener(MouseEvent.CLICK, objATrigger);
objB.addEventListener(MouseEvent.CLICK, objBTrigger);
objC.addEventListener(MouseEvent.CLICK, objCTrigger);
function objATrigger(event: MouseEvent): void {
MovieClip(this.parent).gotoAndPlay(1, "Main");
}
function objBTrigger(event: MouseEvent): void {
MovieClip(this.parent).gotoAndPlay(1, "Main");
}
function objCTrigger(event: MouseEvent): void {
MovieClip(this.parent).gotoAndPlay(1, "Main");
}
The problem is: When I drag the MovieClip (obj) there is a conflict with the event, when release the mouse after the drag, the event Click of MovieClips inside the MovieClip (obj) is fired, how can I fix this? They should only be triggered when there is no drag action.

This is how I handle dragging a parent that has clickable children. The benefit of this method, is that you don't need to do anything to the children (no extra conditions in their click handlers etc), the click event simply doesn't reach them.
You can also hopefully gleam some efficiency tips from the code/comments below:
var wasDragged:Boolean = false;
var dragThreshold:Point = new Point(10,10);
// ^ how many pixels does it need to move before it's considered a drag
//this is good especially on touchscreens as it's easy to accidentally drag the item a couple pixels when clicking.
var dragStartPos:Point = new Point(); //to store drag origin point to calculate whether a drag occured
var dragOffset:Point = new Point(); //to track the gap between the mouse down point and object's top left corner
obj.addEventListener(MouseEvent.MOUSE_DOWN, startdrag);
obj.addEventListener(MouseEvent.CLICK, dragClick, true); //listen on the capture phase of the event.
//the only reason we listen for click on the draggable object, is to cancel the click event so it's children don't get it
function dragClick(e:Event):void {
//if we deemed it a drag, stop the click event from reaching any children of obj
if(wasDragged) e.stopImmediatePropagation();
}
function startdrag(e: MouseEvent): void {
//reset all dragging vars
wasDragged = false;
dragStartPos.x = obj.x;
dragStartPos.y = obj.y;
//set the offset so the object doesn't jump when first clicked
dragOffset.x = stage.mouseX - obj.x;
dragOffset.y = stage.mouseY - obj.y;
//only add the mouse up listener AFTER the mouse down
stage.addEventListener(MouseEvent.MOUSE_UP, stopdrag);
//mouse_move is more efficient that enter_frame, and only listen for it when dragging
stage.addEventListener(MouseEvent.MOUSE_MOVE, followmouse);
}
function stopdrag(e:MouseEvent = null): void {
//remove the dragging specific listeners
stage.removeEventListener(MouseEvent.MOUSE_UP, stopdrag);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, followmouse);
}
function followmouse(e:MouseEvent): void {
if (obj) {
//do what you need to move the object
obj.x = stage.mouseX - dragOffset.x;
obj.y = stage.mouseY - dragOffset.y;
//check if the obj moved far enough from the original position to be considered a drag
if(!wasDragged
&& (Math.abs(obj.x - dragStartPos.x) > dragThreshold.x
|| Math.abs(obj.y - dragStartPos.y) > dragThreshold.y)
){
wasDragged = true;
}
}
}

I don`t know if this is the best approach, but it was possible to check using the code below:
stage.addEventListener(MouseEvent.MOUSE_DOWN, setmousepos);
brose_trigger.addEventListener(MouseEvent.MOUSE_UP, broseTrigger);
denso_trigger.addEventListener(MouseEvent.MOUSE_UP, densoTrigger);
honda_trigger.addEventListener(MouseEvent.MOUSE_UP, hondaTrigger);
var mousePos: Point = new Point();
function setmousepos(e:MouseEvent): void {
mousePos.x = mouseX;
}
function broseTrigger(e:MouseEvent): void {
if(mousePos.x == mouseX){
MovieClip(this.parent).gotoAndPlay(1, "Main");
}
}
function densoTrigger(event:MouseEvent): void {
if(mousePos.x == mouseX){
MovieClip(this.parent).gotoAndPlay(1, "Main");
}
}
function hondaTrigger(event:MouseEvent): void {
if(mousePos.x == mouseX){
MovieClip(this.parent).gotoAndPlay(1, "Main");
}
}
When MOUSE_DOWN event is triggered, I store the mouse.x position in a variable, after that in the MOUSE_UP event, I compare the stored position with the actual position, if equals, TÃDÃ!

Do add condition in objATrigger function to check if dragging is false
function objATrigger(event: MouseEvent): void {
if(!MovieClip(root).dragging){
MovieClip(this.parent).gotoAndPlay(1, "Main");
}
}

Related

Restore dragged movieclips to their original position as they are dragged outside the stage in action script 3

I am creating a drag and drop the game for kids and I realized that when the kid drags a movie clip by mistake outside the stage the movie clip hangs where it is dragged onto and doesn't return back to its original position or it overlaps over other movie clips.
Thanks in advance
the code I am basically using is:
* square_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp2);
square_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt2);
function pickUp2(event: MouseEvent): void {
square_mc.startDrag(true);
event.target.parent.addChild(event.target);
startX = event.currentTarget.x;
startY = event.currentTarget.y;
}
function dropIt2(event: MouseEvent): void {
square_mc.stopDrag();
var myTargetName:String = "target" + event.target.name;
var myTarget:DisplayObject = getChildByName(myTargetName);
if (event.target.dropTarget != null && event.target.dropTarget.parent ==
myTarget){
event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickUp2);
event.target.removeEventListener(MouseEvent.MOUSE_UP, dropIt2);
event.target.buttonMode = false;
event.target.x = myTarget.x;
event.target.y = myTarget.y
} else {
event.target.x = startX;
event.target.y = startY;
}
}*
What you need to do is to preserve the initial position of the clip somewhere and then use it.
Basic algorithm I can think of can look as follows: 1 - player starts dragging a clip, init position is saved 2 - player releases the clip.
Two outcomes are possible: (a): the clip is on the right position or (b): it is misplaced. In case (b) you just need to assign initial coordinates back to the clip.
Very simple example:
private const initialCoords: Dictionary = new Dictionary();
private function saveInitialCoords(clip: DisplayObject): void {
initialCoords[clip] = new Point(clip.x, clip.y);
}
private funciton retreiveInitialCoords(clip: DisplayObject): Point {
return initialCoords[clip]; // it would return null if there is no coords
}
UPD: As it was pointed by #kaarto my answer might be irrelevant. If the issue is to keep the dragging movieclip
within some bounds I usually use something like this:
private var currentTarget: DisplayObject; // clip we're dragging currently
private var areaBounds: Rectangle = new Rectangle(0, 0, stage.stageWidth, stage.stageHeight); // you might want to ensure stage is not null.
private function startDrag(e: MouseEvent): void {
// I'll drop all checks here. Normally you want to ensure that currentTarget is null or return it to initial position otherwise
currentTarget = e.currentTarget as DisplayObject;
saveInitialCoords(currentTarget);
addEventListener(MouseEvent.MOUSE_MOVE, checkAreaBounds);
}
private funciton stopDrag(e: MouseEvent): void {
// some checks were dropped.
if (clipIsOnDesiredPlace(currentTarget)) {
// do something
} else {
const initialCoords: Point = retreiveInitialCoords(currentTarget);
currentTarget.x = initialCoords.x;
currentTarget.y = initialCoords.y;
}
currentTarget = null;
removeEventListener(MouseEvent.MOUSE_MOVE, checkAreaBounds);
}
private funciton checkAreaBounds(e: MouseEvent): void {
// you might need to convert your coords localToGlobal depending on your hierarchy
// this function gets called constantly while mouse is moving. So your clip won't leave areaBounds
var newX: Number = e.stageX;
var newY: Number = e.stageY;
if (currentTarget) {
if (newX < areaBounds.x) newX = areaBounds.x;
if (newY < areaBounds.y) newY = areaBounds.y;
if (newX + currentTarget.width > areaBounds.x + areaBounds.width) newX = areaBounds.x + areaBounds.width - currentTarget.width;
if (newY + currentTarget.height > areaBounds.y + areaBounds.heght) newY = areaBounds.y + areaBounds.height - currentTarget.height;
currentTarget.x = newX;
currentTarget.y = newY;
}
}
... somewhere ...
// for each clip you're going to interact with:
for each (var c: DisplayObject in myDraggableClips) {
c.addEventListener(MouseEvent.MOUSE_DOWN, startDrag);
c.addEventListener(MouseEvent.MOUSE_UP, stopDrag);
}
Another option (if you don't want to limit the area with some bounds) is to use MouseEvent.RELEASE_OUTSIDE event and return a clip to it's initial position once it gets released:
stage.addEventListener(MouseEvent.RELEASE_OUTSIDE, onMouseReleaseOutside);
private function onMouseReleaseOutside(e:MouseEvent):void {
// return clip to it's position.
}
More info you can find in documentation: https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/events/MouseEvent.html#RELEASE_OUTSIDE

My Character Won't Move :( Multiple .as files AS3

I have a few .as files. They are: MainClass.as, FrontEnd.as, Levels.as, and Hero.as. My problem (as far as I know) is in my Hero.as file. Let me descibe how I have it all set up thusfar because I have been a bit concerned that there are better ways of doing things in AS3.
MainClass.as makes a variable of FrontEnd (menus, namely the main menu) and calls it up (addChild).
FrontEnd.as are my menus. buttons and whatnot...
Levels.as right now just calls up level 1 when the start new game button is pressed on the main menu. Had one hell of a time figuring out how to use functions from a different .as file. Hero.as I will add my code for. I'm posting the whole thing because I don't know where my problem is.
public class Hero extends MovieClip
{
public var roger:player = new player();
private var animationState:String = "down";
public var facing:String = "down";
private var isLeft:Boolean = false;
private var isRight:Boolean = false;
private var isUp:Boolean = false;
private var isDown:Boolean = false;
public var currentPlayer:MovieClip = roger;
public function Hero()
{
addEventListener(Event.ENTER_FRAME, loop);
addEventListener(Event.ADDED_TO_STAGE, onStage);
trace(currentPlayer);
}
public function onStage( event:Event ):void
{
removeEventListener( Event.ADDED_TO_STAGE, onStage );
}
public function addCurrentPlayer():void
{
roger.x = stage.stageWidth * .5;
roger.y = stage.stageHeight * .5;
addChild(roger);
currentPlayer = roger;
setBoundaries();
}
public function keyDownHandler(event:KeyboardEvent)
{
if (event.keyCode == 39)//right press
{
isRight = true;
}
if (event.keyCode == 37)//left pressed
{
isLeft = true;
}
if (event.keyCode == 38)//up pressed
{
isUp = true;
}
if (event.keyCode == 40)//down pressed
{
isDown = true;
}
}
public function keyUpHandler(event:KeyboardEvent)
{
if (event.keyCode == 39)//right released
{
isRight = false;
}
if (event.keyCode == 37)//left released
{
isLeft = false;
}
if (event.keyCode == 38)//up released
{
isUp = false;
}
if (event.keyCode == 40)//down released
{
isDown = false;
}
}
public function loop(Event):void
{
if (currentPlayer == null)
{
addCurrentPlayer();//make sure at least roger is on the screen
}
currentPlayer.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
currentPlayer.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
//----------------------------------0
//Animation States
//----------------------------------0
if (isDown == true)
{
currentPlayer.y += 5;
animationState = "walk_down";
facing = "down";
currentPlayer.gotoAndStop(animationState);
}
else if (isUp == true)
{
currentPlayer.y -= 5;
animationState = "walk_up";
facing = "up";
currentPlayer.gotoAndStop(animationState);
}
else if (isRight == true)
{
currentPlayer.x += 5;
animationState = "walk_right";
facing = "right";
currentPlayer.gotoAndStop(animationState);
}
else if (isLeft == true)
{
currentPlayer.x -= 5;
animationState = "walk_left";
facing = "left";
currentPlayer.gotoAndStop(animationState);
}
//----------------------------------0;
//IDLE STATES
//----------------------------------0
else if (isDown == false)
{
currentPlayer.gotoAndStop(facing);
}
else if (isUp == false)
{
currentPlayer.gotoAndStop(facing);
}
else if (isRight == false)
{
currentPlayer.gotoAndStop(facing);
}
else if (isLeft == false)
{
currentPlayer.gotoAndStop(facing);
}
}
public function setBoundaries():void
{
var halfHeight:int = currentPlayer.height * .5;
var halfWidth:int = currentPlayer.width * .5;
if(currentPlayer.y <= 1)
{
currentPlayer.y += halfHeight;
}
else if(currentPlayer.y > stage.stageHeight)
{
currentPlayer.y -= halfHeight;
}
else if(currentPlayer.x <= 1)
{
currentPlayer.x += halfWidth;
}
else if(currentPlayer.x > stage.stageWidth)
{
currentPlayer.x -= halfWidth;
}
}
}
}
trace(currentPlayer); is giving me [object player] instead of the instance name "roger". (Later on I want more playable characters.) I'm not sure if the problem is there or in my levels file, which I'll post here. (not as long as Hero.as)
public class Levels extends MovieClip
{
var currentLevel:MovieClip;
public function Levels()
{
addEventListener(Event.ADDED_TO_STAGE, onStage);
}
private function onStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, gotoLevelOne);
}
public function gotoLevelOne():void
{
var levelOne:LevelOne = new LevelOne();
var hero:Hero = new Hero();
addChild(hero);
levelOne.x = stage.stageWidth * .5;
levelOne.y = stage.stageHeight * .5;
addChild(levelOne);
currentLevel = levelOne;
hero.currentPlayer.x = 100;
hero.currentPlayer.y = 100;
addChild(hero.currentPlayer);
}
}
}
If I remove = roger; from var currentPlayer:MovieClip = roger; it gives me #1009 null object even though I told it in addCurrentPlayer() to change currentPlayer to roger. On level 1, everything shows up but I can't move my character. I know that it worked when I was working on his animations and I would call him to the main menu. Everything worked on him. What's the problem now?
Firstly, there's a lot of things wrong with your code:
In your Hero Class, the 'onStage' Event handler doesn't actually do anything other than remove the event listener that triggers it. While it's good practice to remove the event listener, there should be some other purpose to the Event handler. If there isn't you can remove it and not bother listening for the ADDED_TO_STAGE Event.
Similarly, in your Levels Class 'onStage' Event handler you attempt to remove the event, but name the wrong handler. I assume you want to remove the event handler and then run the 'gotoLevelOne' method. If so, just have the Event.ADDED_TO_STAGE listener call 'gotoLevelOne' and then remove the Event listener there:
public function Levels()
{
addEventListener(Event.ADDED_TO_STAGE, gotoLevelOne);
}
public function gotoLevelOne():void
{
removeEventListener(Event.ADDED_TO_STAGE, gotoLevelOne);
// class continues....
OK, so to your question:
You will be getting the null error because you are referring to currentPlayer from outside the Hero Class, before calling addCurrentPlayer (where it is set).
If you temporarily define currentPlayer as a private variable, the compiler should give you a line number where you first refer to currentPlayer from OUTSIDE the Hero Class (the error will be something like 'Class X is trying to access a private (or non-existent) property of Y Class').
You can then sort out WHY you are accessing currentPlayer before calling addCurrentPlayer. You may also want to think about if currentPlayer NEEDS to be public (if so, then what is 'addCurrentPlayer' for? That function effectively works as a setter for currentPlayer).
EDIT:
At the moment you are adding new KEY_DOWN and KEY_UP event listeners EVERY frame of your game loop. This is unnecessary. Add them both ONCE in the initialisation of your game (perhaps in your Hero's onStage handler), and count on them to trigger the appropriate handlers.
You will want to add the KEY_DOWN and KEY_UP listeners to 'stage', not currentPlayer, so:
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDownHandler);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUpHandler);
You will need to add the listeners AFTER your Hero instance has been added to the Stage though, so it has access to 'stage'. That's why it makes sense to add the listeners in the Hero's onstage handler.

AS3 vertical shooter: Mouse click not working

I'm just trying to make a simple vertical shooter, one where the player's ship is controlled by the mouse and fires a laser when you click the mouse. However, when I try running the code, I keep getting the same error message:
"1046: Type was not found or was not a compile-time constant: MouseEvent."
The thing is, I declared the MouseEvent. I know I did. It is as follows:
--==--
package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.events.MouseEvent;
public class SpaceShooter_II extends MovieClip //The public class extends the class to a movie clip.
{
public var army:Array; //the Enemies will be part of this array.
///*
//Laser Shots and Mouse clicks:
import flash.events.MouseEvent;
public var playerShot:Array; //the player's laser shots will fill this array.
public var mouseClick:Boolean;
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseGoDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseGoUp);
stage.addEventListener(Event.ENTER_FRAME, onTick);
//*/
//Back to the rest of the code:
public var playerShip:PlayerShip; //This establishes a variable connected to the PlayerShip AS.
public var onScreen:GameScreen; //This establishes a variable that's connected to the GameScreen AS.
public var gameTimer:Timer; //This establishes a new variable known as gameTimer, connected to the timer utility.
///*
//Functions connected to Shooting via mouse-clicks:
public function mouseGoDown(event:MouseEvent):void
{
mouseClick = true;
}
public function mouseGoUp(event:MouseEvent):void
{
mouseClick = false;
}
//*/
//This function contains the bulk of the game's components.
public function SpaceShooter_II()
{
//This initiates the GameScreen.
onScreen = new GameScreen;
addChild ( onScreen );
//This sets up the enemy army.
army = new Array(); //sets the "army" as a NEW instance of array.
var newEnemy = new Enemy( 100, -15); //This will create new enemies. There's new var newEnemy statement, hence we call THIS a var.
army.push ( newEnemy ); //the new enemy is added to the army.
addChild( newEnemy ); //the new enemy is added to the game.
//This sets up the player's avatar, a spaceship.
playerShip = new PlayerShip(); //This invokes a new instance of the PlayerShip...
addChild( playerShip ); //...And this adds it to the game.
playerShip.x = mouseX; //These two variables place the "playerShip" on-screen...
playerShip.y = mouseY; //...at the position of the mouse.
///*
//This sets up the player's laser shots:
playerShot = new Array(); //sets the "army" as a NEW instance of array.
var goodShot = new goodLaser( playerShip.x, playerShip.y); //This will create new enemies. There's new var newEnemy statement, hence we call THIS a var.
playerShot.push ( goodShot ); //the new enemy is added to the army.
addChild( goodShot ); //the new enemy is added to the game.
//*/
//This sets up the gameTimer, where a lot of the action takes place.
gameTimer = new Timer( 25 );
gameTimer.addEventListener( TimerEvent.TIMER, onTick );
gameTimer.start();
}
//This function contains the things that happen during the game (player movement, enemy swarms, etc.)
public function onTick( timerEvent:TimerEvent ):void
{
//This "if" statement is where the array that contains the enemy ships is initialized.
if ( Math.random() < 0.05 ) //This sets the number of ships showing up at once.
{
var randomX:Number = Math.random() * 800 //Generates a random number between 0 and 1.
var newEnemy:Enemy = new Enemy ( randomX, -15 ); //This shows where the enemy starts out--at a random position on the X plane, but at a certain points on the Y plane.
army.push( newEnemy ); //This adds the new enemy to the "army" Array.
addChild( newEnemy ); //This makes the new enemy part of the game.
}
//This "for" statement sends the enemies downward on the screen.
for each (var enemy:Enemy in army) //Every time an enemy is added to the "army" array, it's sent downward.
{
enemy.moveDown(); //This is the part that sends the enemy downward.
//And now for the collision part--the part that establishes what happens if the enemy hits the player's spaceship:
if ( playerShip.hitTestObject ( enemy ) ) //If the playerShip makes contact with the enemy...
{
gameTimer.stop(); //This stops the game.
dispatchEvent( new PlayerEvent(PlayerEvent.BOOM) ); //This triggers the game over screen in the PlayerEvent AS
}
}
//This, incidentally, is the player's movement controls:
playerShip.x = mouseX;
playerShip.y = mouseY;
///*
//And this SHOULD be the shooting controls, if the mouse function would WORK...
if ( mouseClick = true )
{
var goodShot = new goodLaser( playerShip.x, playerShip.y); //This will create new lasers. There's new variable in the statement, hence we call THIS a variable.
playerShot.push ( goodShot ); //the new laser is added to the army.
addChild( goodShot ); //the new laser is added to the game.
}
for each (var goodlaser: goodLaser in goodShot)
{
goodlaser.beamGood();
}
//*/
}
}
}
--==--
Sorry if the brackets are coming in uneven, I just wanted to outline the code in its entirety, and show the parts I added where things started going wrong, so someone can tell me what I need to do to make this work.
Basically, everything else works...but when I work on the things connected to the mouse clicking and the array with the lasers, the program stops working. The error seems to be connected to the functions "mouseGoUp" and "mouseGoDown," but I'm not sure how to fix that.
This assignment is due March 8. Can someone help me, please?
Add this import flash.events.MouseEvent; to the top of your class and it should work. You need to import everything you use. That's why you get that error.
As well as importing MouseEvent, in the initialisation of your game, you should add event listeners to the stage which listen for the MOUSE_DOWN and MOUSE_UP events:
stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseGoDown);
stage.addEventListener(MouseEvent.MOUSE_UP, mouseGoUp);
What would be simpler, though, would be to do away with the 'mouseClick' variable and have just a single MouseEvent listener which listens for the MOUSE_DOWN event and trigger your missle launch from the handler.
I had a game like this if you want the entire source i can give it to you but the main parts are
var delayCounter:int = 0;
var mousePressed:Boolean = false;
var delayMax:int = 5;//How rapid the fire is
var playerSpeed:int = 5;
var bulletList:Array = [];
var bullet:Bullet;
var upPressed:Boolean = false;
var downPressed:Boolean = false;
var leftPressed:Boolean = false;
var rightPressed:Boolean = false;
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);
stage.addEventListener(KeyboardEvent.KEY_DOWN, fl_SetKeyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_UnsetKeyPressed);
function loop(e:Event):void
{
player.rotation = Math.atan2(mouseY - player.y,mouseX - player.x) * 180 / Math.PI + 90;
if (bulletList.length > 0)
{
for each (bullet in bulletList)
{
bullet.bulletLoop();
}
}
if (mousePressed)
{
delayCounter++;
if ((delayCounter == delayMax))
{
shootBullet();
delayCounter = 0;
}
}
if (upPressed)
{
player.y -= playerSpeed;
}
if (downPressed)
{
player.y += playerSpeed;
}
if (leftPressed)
{
player.x -= playerSpeed;
}
if (rightPressed)
{
player.x += playerSpeed;
}
}
function mouseDownHandler(e:MouseEvent):void
{
mousePressed = true;
}
function mouseUpHandler(e:MouseEvent):void
{
mousePressed = false;
}
function shootBullet():void
{
var bullet:Bullet = new Bullet(stage,player.x,player.y,player.rotation - 90);
bulletList.push(bullet);
stage.addChildAt(bullet,1);
}
function fl_SetKeyPressed(event:KeyboardEvent):void
{
if (event.keyCode == 87)
{
upPressed = true;
}
if (event.keyCode == 83)
{
downPressed = true;
}
if (event.keyCode == 65)
{
leftPressed = true;
}
if (event.keyCode == 68)
{
rightPressed = true;
}
}
function fl_UnsetKeyPressed(event:KeyboardEvent):void
{
if (event.keyCode == 87)
{
upPressed = false;
}
if (event.keyCode == 83)
{
downPressed = false;
}
if (event.keyCode == 65)
{
leftPressed = false;
}
if (event.keyCode == 68)
{
rightPressed = false;
}
}
BULLET CLASS
package
{
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
public class Bullet extends MovieClip
{
private var stageRef:Stage;
private var speed:Number = 10;//speed that the bullet will travel at
private var xVel:Number = 5;
private var yVel:Number = 5;
private var rotationInRadians = 0;
public function Bullet(stageRef:Stage, X:int, Y:int, rotationInDegrees:Number):void
{
this.stageRef = stageRef;
this.x = X;
this.y = Y;
this.rotation = rotationInDegrees;
this.rotationInRadians = rotationInDegrees * Math.PI / 180;
}
public function bulletLoop():void
{
xVel = Math.cos(rotationInRadians) * speed;
yVel = Math.sin(rotationInRadians) * speed;
x += xVel;
y += yVel;
if (x > stageRef.stageWidth || x < 0 || y > stageRef.stageHeight || y < 0)
{
deleteBullet();
}
}
public function deleteBullet()
{
this.visible=false
this.x=9999
this.y=9999
}
}
}

AS3 Works but I get a ReferenceError: Error #1069 Property startDrag not found

I am trying to make a simple project when you click a button a draggable MovieClip is added to the stag and when you click it releases the MovieClip to the X/Y where you clicked, you can then pickup the MovieClip and drag it into a bin (MovieClip) where it destroys itself. The code is working great I can make multiple Movieclips with the button and they are all destroyed when I drag them in the bin however I don't like having "Error Codes".
import flash.events.MouseEvent;
var rubbish:my_mc = new my_mc();
btntest.addEventListener(MouseEvent.CLICK, makeRubbish);
function makeRubbish (event:MouseEvent):void {
addChild(rubbish);
rubbish.x = mouseX - 10;
rubbish.y = mouseY - 10;
rubbish.width = 50;
this.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
rubbish.buttonMode = true;
}
function stopDragging (event:MouseEvent):void {
rubbish.stopDrag()
event.target.addEventListener(MouseEvent.CLICK, startDragging);
rubbish.buttonMode = true;
if (event.target.hitTestObject(bin))
{
trace("hit");
event.target.name = "rubbish";
removeChild(getChildByName("rubbish"));
}
}
function startDragging (event:MouseEvent):void {
event.target.startDrag();
this.addEventListener(MouseEvent.CLICK, stopDragging);
}
Some Pointers:
The target property of an Event is not always what it seems. It actually refers to the current phase in the event bubbling process. Try using the currentTarget property.
I would also recommend tying the stopDragging method to the stage, as sometimes your mouse won't be over the drag as you're clicking.
I would use the MOUSE_UP event as opposed to a CLICK for standard dragging behaviour.
When dragging, keep a global reference to the drag in order to call the stopDrag method on the correct object.
Try This:
import flash.events.MouseEvent;
var rubbish:my_mc = new my_mc();
var dragging:my_mc;
btntest.addEventListener(MouseEvent.CLICK, makeRubbish);
function makeRubbish (event:MouseEvent):void {
addChild(rubbish);
rubbish.x = mouseX - 10;
rubbish.y = mouseY - 10;
rubbish.width = 50;
rubbish.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
rubbish.buttonMode = true;
}
function stopDragging (event:MouseEvent):void {
this.stage.removeEventListener(MouseEvent.MOUSE_UP, stopDragging);
if(dragging !== null){
dragging.stopDrag();
if (event.currentTarget.hitTestObject(bin)){
removeChild(dragging);
}
dragging = null;
}
}
function startDragging (event:MouseEvent):void {
dragging = event.currentTarget as my_mc;
dragging.startDrag();
this.stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
}

Error: #1009: Type Error (Line #114)

I'm sort of a noob to flash, but I am programming a game right now, and I am trying to make my character move but i am getting error #1009 Here is my code in my "GameState".
Basically it errors out on any Keypress, I have my character named player (Player in the library) and it has another movie clip within it named WalkDown (I gave it an instance name of walkDown on the timeline) I am not really sure whats going on. Specifically it errors out on the line where its calling the frame name. Any help would be appreciated!
package {
import flash.display.Stage;
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.geom.Point;
public class GameState extends MovieClip {
private var player:MovieClip;
private var walking:Boolean = false;
// is the character shooting
//private var shooting:Boolean = false;
// wlaking speed
private var walkingSpeed:Number = 5;
private var xVal:Number = 0;
private var yVal:Number = 0;
public function GameState() {
// constructor code
player = new Player();
addChild(player);
player.x = 300;
player.y = 300;
player.gotoAndStop("stance");
this.addEventListener(Event.ADDED_TO_STAGE, initialise);
}
private function initialise(e:Event){
// add a mouse down listener to the stage
//addEventListener(MouseEvent.MOUSE_DOWN, startFire);
// add a mouse up listener to the stage
//addEventListener(MouseEvent.MOUSE_UP, stopFire);
player.addEventListener(Event.ENTER_FRAME,motion);
stage.addEventListener(KeyboardEvent.KEY_UP,onKey);
// add a keyboard down listener
stage.addEventListener(KeyboardEvent.KEY_DOWN, offKey);
stage.focus = stage;
// Add keyboard events
}
private function motion(e:Event):void{
// if we are currently holding the mouse down
//if (shooting){
//FIRE
//fire();
//}
player.x += xVal;
player.y += yVal;
}
//private function startFire(m:MouseEvent){
//shooting = true;
//}
//private function stopFire(m:MouseEvent){
//shooting = false;
//}
private function onKey(evt:KeyboardEvent):void
{
trace("key code: "+evt.keyCode);
switch (evt.keyCode)
{
case Keyboard.W :
yVal = walkingSpeed;
if (! walking)
{
trace("walking up");
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.S :
yVal = - walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.A :
xVal = walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
case Keyboard.D :
xVal = walkingSpeed;
if (! walking)
{
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;
}
}
private function offKey(evt:KeyboardEvent):void
{
switch (evt.keyCode)
{
case Keyboard.W :
//for now just reset velocity to zero
yVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.S :
//for now just reset velocity to zero
yVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.A :
//for now just reset velocity to zero
xVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
case Keyboard.D :
//for now just reset velocity to zero
xVal = 0;
//also stop walk cycle etc.
player.gotoAndStop("stance");
//don't forget to update your Boolean
walking = false;
break;
}
}
// Players Motion
private function fire():void{
var b= new Bullet();
// set the position and rotation of the bullet
b.rotation = rotation;
b.x = x;
b.y = y;
// add bullets to list of bullets
MovieClip(player).bullets.push(b);
// add bullet to parent object
player.addChild(b);
// play firing animation
player.shooting.gotoAndPlay("fire");
}
}
}
You were saying the Error #1009 ( Cannot access a property or method of a null object reference ) arises when you do
player.walkDown.gotoAndPlay("walking");
If so, that is because you have to first go to the frame where the WalkDown MovieClip is in before you can access it.
If say your "stance" frame is in frame 1 and your WalkDown MovieClip is in frame 2. Your code in the onKey function should look like:
case Keyboard.W :
yVal = walkingSpeed;
if (! walking)
{
trace("walking up");
player.gotoAndStop(2); // player.walkDown is now accessible //
player.walkDown.gotoAndPlay("walking");
walking = true;
}
break;