ActionScript 3: Zoom functions - drag does not show - actionscript-3

I've included a zoom functionality similar to the one explained at this website: http://www.flashandmath.com/howtos/zoom/
Even though it does indeed work in terms of the possibility of moving the image on my stage, the drag-animation is not present, meaning there will be no "movement" of my image, just a sudden change in position.
The problem followed my attempt to change the concept from timeline-based to class-based.
Here is my Main class:
package
{
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.display.Shape;
import fl.transitions.Fly;
import fl.motion.MatrixTransformer;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.ui.Mouse;
public class Main extends Sprite
{
public static var scale:Number = 1;
private var _rootMC:MovieClip;
// ------------------------------
public var bg_image:Sprite;
public var spImage:Sprite;
public var mat:Matrix;
public var mcIn:MovieClip;
public var mcOut:MovieClip;
public var boardWidth:int = 980;
public var boardHeight:int = 661;
public var boardMask:Shape;
public var externalCenter:Point;
public var internalCenter:Point;
public static var scaleFactor:Number = 0.8;
public static var minScale:Number = 0.25;
public static var maxScale:Number = 10.0;
//-------------------------------
public function Main(rootMC:MovieClip)
{
_rootMC = rootMC;
bg_image = new image();
this.graphics.beginFill(0xB6DCF4);
this.graphics.drawRect(0,0,boardWidth,boardHeight);
this.graphics.endFill();
spImage = new Sprite();
this.addChild(spImage);
boardMask = new Shape();
boardMask.graphics.beginFill(0xDDDDDD);
boardMask.graphics.drawRect(0,0,boardWidth,boardHeight);
boardMask.graphics.endFill();
boardMask.x = 0;
boardMask.y = 0;
this.addChild(boardMask);
spImage.mask = boardMask;
minScale = boardWidth / bg_image.width;
mcIn = new InCursorClip();
mcOut = new OutCursorClip();
bg_image.addChild(mcIn);
bg_image.addChild(mcOut);
bg_image.scaleX = minScale;
bg_image.scaleY = minScale;
spImage.addChild(bg_image);
spImage.addChild(mcIn);
spImage.addChild(mcOut);
spImage.addEventListener(MouseEvent.MOUSE_DOWN, startDragging);
_rootMC.stage.addEventListener(MouseEvent.MOUSE_UP, stopDragging);
spImage.addEventListener(MouseEvent.CLICK, zoom);
_rootMC.stage.addEventListener(KeyboardEvent.KEY_DOWN, keyHandler);
_rootMC.stage.addEventListener(KeyboardEvent.KEY_UP, keyHandler);
}
private function startDragging(mev:MouseEvent):void
{
spImage.startDrag();
}
private function stopDragging(mev:MouseEvent):void
{
spImage.stopDrag();
}
private function zoom(mev:MouseEvent):void
{
if ((!mev.shiftKey)&&(!mev.ctrlKey))
{
return;
}
if ((mev.shiftKey)&&(mev.ctrlKey))
{
return;
}
externalCenter = new Point(spImage.mouseX,spImage.mouseY);
internalCenter = new Point(bg_image.mouseX,bg_image.mouseY);
if (mev.shiftKey)
{
bg_image.scaleX = Math.max(scaleFactor*bg_image.scaleX, minScale);
bg_image.scaleY = Math.max(scaleFactor*bg_image.scaleY, minScale);
}
if (mev.ctrlKey)
{
bg_image.scaleX = Math.min(1/scaleFactor*bg_image.scaleX, maxScale);
bg_image.scaleY = Math.min(1/scaleFactor*bg_image.scaleY, maxScale);
}
mat = this.transform.matrix.clone();
MatrixTransformer.matchInternalPointWithExternal(mat,internalCenter,externalCenter);
bg_image.transform.matrix = mat;
}
private function keyHandler(ke:KeyboardEvent):void
{
mcIn.x = spImage.mouseX;
mcIn.y = spImage.mouseY;
mcOut.x = spImage.mouseX;
mcOut.y = spImage.mouseY;
mcIn.visible = ke.ctrlKey;
mcOut.visible = ke.shiftKey;
if (ke.ctrlKey || ke.shiftKey)
{
Mouse.hide();
}
else
{
Mouse.show();
}
}
}
}
Here is my image class:
package {
import fl.motion.MatrixTransformer;
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.display.Shape;
import fl.transitions.Fly;
import fl.motion.MatrixTransformer;
import flash.events.MouseEvent;
public class image extends MovieClip
{
public function image()
{
this.width = 980
this.height = 500
this.y = 0
this.x = 0
}
}
I know this is a lot of code, but I am really stuck :(

On your MOUSE_DOWN handler, you need to start listening to the MOUSE_MOVE event.
On your MOUSE_UP handler, you need to stop listening to the MOUSE_MOVE event.
Not sure if you are already doing this.
In your MOUSE_MOVE event handler, you need to update the x / y positions of the image, in a similar way to what you are probably doing on the MOUSE_UP handler.

Related

as3 button getting clicked 50 px below button

I have an issue. I've narrowed down to my button class where if I click 50-100px below the button sprite area, the mouse.click event listener is triggered.
At one point I thought that a nested issue with sprite children could have caused it, but even adding the button straight to stage has the same effect.
I rewrote the button class from scratch and the same thing is happened.
I'm unsure if this is something that happens because I'm writing pure as3 with the flex framework or something else. Here is the class for the button code:
package org.project.ui
{
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.Graphics;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import flash.display.Shape;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
import org.project.controller.IController;
import flash.utils.getQualifiedClassName;
/**
*
*
*/
public class CustomButton2 extends CustomSprite
{
protected var _button:Sprite;
protected var _buttonFunction:Function = null;
protected var _label:String = "";
protected var _textField:TextField;
protected var _textFormat:TextFormat;
protected var _font:String = "Arial";
protected var _fontSize:int = 12;
protected var _fontColor:uint = 0x000000;
protected var _buttonWidth:int = 110;
protected var _buttonHeight:int = 30;
public function CustomButton2(label:String, id:String, w:int, h:int, buttonFunction:Function = null)
{
super(id, content);
_label = label;
_buttonWidth = w;
_buttonHeight = h;
_button = makeButton(label, w, h, buttonFunction);
addButtonListeners();
addChild(_button);
}
protected function makeButton(label:String, w:int, h:int, buttonFunction:Function = null):Sprite {
_button = new Sprite();
_button = drawButton(_button);
_button.useHandCursor = true;
_button.buttonMode = true;
_button.mouseChildren = false;
_button = addTextField(label, _button);
return _button;
}
protected function addTextField(label:String, button:Sprite):Sprite {
_textFormat = new TextFormat(_font, _fontSize, _fontColor, false, null, null, null, null, TextFormatAlign.CENTER);
_textField = new TextField();
_textField.defaultTextFormat = _textFormat;
_textField.name = "textField_" + id;
_textField.text = _label;
_textField.selectable = false;
button.addChild(_textField);
return button;
}
protected function addButtonListeners():void {
_button.addEventListener(MouseEvent.CLICK, mouseClick);
_button.addEventListener(MouseEvent.ROLL_OVER, mouseRollover);
_button.addEventListener(MouseEvent.ROLL_OUT, mouseRollOut);
}
protected function mouseClick(e:MouseEvent) {
e.stopPropagation();
if (_buttonFunction) {
_buttonFunction();
}
changeButtonDisplay();
trace("click");
}
protected function mouseRollover(e:MouseEvent) {
changeButtonDisplay(0xFF0000);
}
protected function mouseRollOut(e:MouseEvent) {
changeButtonDisplay(0xFFCC00);
}
protected function changeButtonDisplay(u:uint = 0xFF0000, w:int = 110, h:int = 30):void {
_button = drawButton(_button, w, h, u);
}
protected function drawButton(button:Sprite, w:int = 110, h:int = 30, u:uint = 0xFFCC00):Sprite{
button.graphics.beginFill(u);
button.graphics.lineStyle(1);
button.graphics.drawRoundRect(0, 0, w, h, 20);
button.graphics.endFill();
button = addTextField(_label, button);
return button;
}
}
}
Any suggestions would greatly be appreciated.
Most likely your TextField is extending past the rest of your button.
It doesn't appear as though your setting the text field's bounds, so it will be the default (usually a 100x100 square).
I suggest explicitly setting the text field's width and height to match your button.
_textField.width = _buttonWidth;
_textField.height = _buttonHeight;
Or instead, if you want all the text visible no matter what, you could use the autoSize property to make the text field bounds match the actual text.
_textField.autoSize = TextFieldAutoSize.LEFT;

Actionscript 3: Error #1009: Cannot access a property or method of a null object reference. (parent)

This is a bit difficult to explain, but I will try.
In my Main() class, let's say I have the main movieclip (bg_image) being created, and also some lines that create an instance of another class. (look at the code below)
var route = Route(Airport.return_Route);
This route instance, is then purposed to dynamically add sprite-childs to the main background from the Main() class.
I have tried to to this with the following line:
new_flight = new Flight(coordinates)
Main.bg_image.addChild(new_flight);
This seem to work pretty fine. Let's switch focus to the new_flight instance. At the Flight class, this line trace(this.parent) would return "[object Image]".I would consider this successful so far since my intention is to add the new_flight as child to bg_image, which I guess is an "object image".
The problem, however, occurs when trying to delete the "new_flight"-instance. Obviously the ideal way of doing this would be through bg_image with removeChild.
But, when my script reaches this line: Main.bg_image.removeChild(this), my script stops and returns ArgumentError: Error #2025: The supplied DisplayObject must be a child of the caller., at that line. I have also tried replacing Main.bg_image.removeChild(this) with this.parent.removeChild(this), with no luck.
I think the solution may be to use some sort of "EventDispatching"-method. But I haven't fully understood this concept yet...
The code follows. Please help. I have no idea how to make this work...
Main class:
package
{
import flash.display.MovieClip;
import flash.utils.Dictionary;
import flash.events.MouseEvent;
import flash.display.Sprite;
import flash.text.TextField;
import fl.controls.Button;
import flash.display.DisplayObject;
import Airport;
public class Main extends Sprite
{
// ------------------------
// Buttons
public var create_new_route;
public var confirm_new_route;
// images
public static var bg_image:MovieClip;
public var airport:MovieClip;
//-------------------------------
public var routeArray:Array;
public static var airportDict:Dictionary = new Dictionary();
public static var collectedAirportArray:Array = new Array();
public function Main()
{
addEventListener(Event.ADDED_TO_STAGE, init);
create_new_route = new Button();
create_new_route.label = "Create new route";
create_new_route.x = 220;
create_new_route.y = 580;
this.addChild(create_new_route)
create_new_route.addEventListener(MouseEvent.CLICK, new_route)
confirm_new_route = new Button();
confirm_new_route.label = "Confirm route";
confirm_new_route.x = 220;
confirm_new_route.y = 610;
this.addChild(confirm_new_route)
confirm_new_route.addEventListener(MouseEvent.CLICK, confirm_route)
}
public function init(e:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
bg_image = new Image();
addChild(bg_image);
S_USA["x"] = 180.7;
S_USA["y"] = 149.9;
S_USA["bynavn"] = "New York";
S_Norway["x"] = 423.7;
S_Norway["y"] = 76.4;
S_Norway["bynavn"] = "Oslo";
S_South_Africa["x"] = -26;
S_South_Africa["y"] = 146;
S_South_Africa["bynavn"] = "Cape Town";
S_Brazil["x"] = 226;
S_Brazil["y"] = 431.95;
S_Brazil["bynavn"] = "Rio de Janeiro";
S_France["x"] = 459.1;
S_France["y"] = 403.9;
S_France["bynavn"] = "Paris";
S_China["x"] = 716.2;
S_China["y"] = 143.3;
S_China["bynavn"] = "Beijing";
S_Australia["x"] = 809.35;
S_Australia["y"] = 414.95;
S_Australia["bynavn"] = "Sydney";
// ----------------------------------------------------
airportDict["USA"] = S_USA;
airportDict["Norway"] = S_Norway;
airportDict["South Africa"] = S_South_Africa;
airportDict["Brazil"] = S_Brazil;
airportDict["France"] = S_France;
airportDict["China"] = S_China;
airportDict["Australia"] = S_Australia;
for (var k:Object in airportDict)
{
var value = airportDict[k];
var key = k;
startList.addItem({label:key, data:key});
sluttList.addItem({label:key, data:key});
var airport:Airport = new Airport(key,airportDict[key]["bynavn"]);
airport.koordinater(airportDict[key]["x"], airportDict[key]["y"]);
collectedAirportArray.push(airport);
airport.scaleY = minScale;
airport.scaleX = minScale;
bg_image.addChild(airport);
}
// --------------------------------------------
// --------------------------------------------
// -----------------------------------------------
}
private function new_route(evt:MouseEvent):void
{
Airport.ROUTING = true;
}
public function confirm_route(evt:MouseEvent):void
{
Airport.ROUTING = false;
trace(Airport.return_ROUTE);
var route = new Route(Airport.return_ROUTE); // ***
this.addChild(route); // **
Airport.return_ROUTE = new Array();
}
}
}
Airport class:
package
{
import flash.display.MovieClip;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.SimpleButton;
import flash.display.Stage;
import flash.text.TextField;
import flash.text.TextFormat;
import flashx.textLayout.formats.Float;
public class Airport extends MovieClip
{
public static var ROUTING = false;
public static var return_ROUTE:Array = new Array();
//-----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
protected var navn:String;
protected var bynavn:String;
// ----------------------------------------------------------------------------
public function Airport(navninput, bynavninput)
{
this.bynavn = bynavninput;
this.navn = navninput;
this.addEventListener(MouseEvent.CLICK, clickHandler);
this.addEventListener(MouseEvent.MOUSE_OVER, hoverHandler);
}
public function zoomHandler():void
{
trace("testing complete");
}
public function koordinater(xc, yc)
{
this.x = (xc);
this.y = (yc);
}
private function clickHandler(evt:MouseEvent):void
{
trace(ROUTING)
if (ROUTING == true)
{
return_ROUTE.push([this.x, this.y])
}
}
private function hoverHandler(evt:MouseEvent):void
{
if (ROUTING == true)
{
this.alpha = 60;
this.width = 2*this.width;
this.height = 2*this.height;
this.addEventListener(MouseEvent.MOUSE_OUT, awayHandler);
}
}
private function awayHandler(evt:MouseEvent):void
{
this.width = 13;
this.height = 13;
}
}
}
Route class
package
{
import flash.events.TimerEvent;
import flash.utils.Timer;
import flash.display.MovieClip;
import Main;
public class Route
{
public var income:Number;
public var routePoints:Array;
private var routeTimer:Timer;
private var new_flight:Flight;
public function Route(route_array:Array)
{
this.routePoints = route_array
routeTimer = new Timer(2000);// 2 second
routeTimer.addEventListener(TimerEvent.TIMER, route_function);
routeTimer.start();
}
private function route_function(event:TimerEvent):void
{
for (var counter:uint = 0; counter < routePoints.length - 1; counter ++)
{
trace("Coords: ", routePoints[counter][0],routePoints[counter][1],routePoints[counter + 1][0],routePoints[counter + 1][1]);
new_flight = new Flight(routePoints[counter][0],routePoints[counter][1],routePoints[counter + 1][0],routePoints[counter + 1][1]);
Main.bg_image.addChild(new_flight);
var checkTimer:Timer = new Timer(15);// 1 second
checkTimer.addEventListener(TimerEvent.TIMER, check_function);
checkTimer.start();
function check_function(event:TimerEvent):void
{
if (new_flight.finished = true)
{
checkTimer.stop();
}
}
}
}
}
}
Flight class
package
{
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.events.Event;
import flash.display.SimpleButton;
import flash.display.Stage;
import flash.events.TimerEvent;
import flash.utils.Timer;
import fl.controls.Button;
import flash.display.DisplayObject;
public class Flight extends MovieClip
{
public static var speed:uint = 1
public var finished:Boolean = false;
protected var absvector:Number;
protected var vector:Array;
protected var myTimer:Timer;
//protected var parentContainer:MovieClip;
protected var utgangspunkt_x;
protected var utgangspunkt_y;
protected var destinasjon_x;
protected var destinasjon_y;
protected var vector_x;
protected var vector_y;
public function Flight(utgangspunkt_x, utgangspunkt_y, destinasjon_x, destinasjon_y):void
{
addEventListener(Event.ADDED_TO_STAGE, init);
this.utgangspunkt_x = utgangspunkt_x;
this.utgangspunkt_y = utgangspunkt_y;
this.x = utgangspunkt_x;
this.y = utgangspunkt_y;
this.destinasjon_x = destinasjon_x + 10;
this.destinasjon_y = destinasjon_y + 10;
this.vector_x = Math.abs(this.destinasjon_x-this.utgangspunkt_x);
this.vector_y = Math.abs(this.destinasjon_y-this.utgangspunkt_y);
this.height = 20;
this.width = 20;
}
public function init(evt:Event):void
{
trace(this.parent)
if (utgangspunkt_x < destinasjon_x)
{
this.rotation = -(Math.atan((utgangspunkt_y-destinasjon_y)/(destinasjon_x-utgangspunkt_x)))/(Math.PI)*180;
}
else
{
this.rotation = 180-(Math.atan((utgangspunkt_y-destinasjon_y)/(destinasjon_x-utgangspunkt_x)))/(Math.PI)*180;
}
absvector = Math.sqrt(Math.pow((destinasjon_x - utgangspunkt_x),2) + Math.pow((utgangspunkt_y - destinasjon_y),2));
vector = [(destinasjon_x - utgangspunkt_x) / absvector,(utgangspunkt_y - destinasjon_y) / absvector];
stage.addEventListener(Event.ENTER_FRAME, movement)
}
private function movement(evt:Event):void
{
if (this.vector_x > this.vector_y)
{
if (destinasjon_x>utgangspunkt_x)
{
if (this.x < destinasjon_x)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
else if (destinasjon_x<utgangspunkt_x)
{
if (this.x > destinasjon_x)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
}
else
{
if (destinasjon_y>utgangspunkt_y)
{
if (this.y < destinasjon_y)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
else if (destinasjon_y<utgangspunkt_y)
{
if (this.y > destinasjon_y)
{
this.x += speed*vector[0];
this.y -= speed*vector[1];
}
else
{
finished = true
Main.bg_image.removeChild(this)
}
}
}
}
}
}
I am confused what your asking and what your trying to do, but I will give it my best shot.
this.addchild(new_class2)
This line adds your object to the display list. Adding another object to the display is done the same way you added the first. Flash adds objects in the sequentially, so the objects you want in the back need to be declared and added first.
This is probably what you want:
var new_flight:Flight = new Flight();
this.addchild(new_flight);
Also you forgot your type declaration for Class2:
var new_class2:Class2 = new Class2();
Try replacing:
Main.bg_image.addChild(new_flight);
with
Main(this.parent).bg_image.addChild(new_flight);
... assuming the 'main' class you refer to is infact named 'Main' and it has a named instance called 'bg_image'
Please leave a comment if it works, I can explain in more detail what is actually happening here.
Why you are adding new_flight to bg_image?
Anyway, if you are adding new_flight to bg_image, then you have bg_image already declared as public static (which I do not recommend),
Try removing the flight in your Flight class it-self like so,
Main.bg_image.removeChild(this) // *
You can also use Event Dispatching instead of declaring bg_image as static.
If you want to remove flight then dispatch event from Flight class to Route class and there you again dispatch event to main class.
And, inside main class capture this event and access the MovieClip.

as3 hitTestPoint detecting alpha

I am trying to make maze where the user draws with mouse and if they hit the wall it erases the line they just drew. I have a png file with alpha that creates the walls of the maze.
I need the user to draw on the alpha but when they hit a non alpha it will trigger an action and erase the line.
Here is the line I am having issues with:
if (myshape.hitTestPoint(theBall.x,theBall.y, true))
Here is the full code:
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.JointStyle;
import flash.display.LineScaleMode;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.*;
public class MazeClass extends Sprite
{
//Are we drawing or not?
private var drawing:Boolean;
public var myshape:Shape;
public var alreadyDrawn:Shape;
public var theBall:Ball = new Ball();
//alreadyDrawn = new Shape();
public function MazeClass()
{
if (stage)
{
myshape = new Shape();
myshape.graphics.lineStyle(12,0x000000);
addChild(myshape);
drawing = false;//to start with
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_MOVE, draw);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
//stage.addEventListener(Event.ENTER_FRAME, checkIt);
addChild(theBall);
}
}
public function startDrawing(event:MouseEvent):void
{
myshape.graphics.moveTo( mouseX, mouseY);
drawing = true;
}
public function draw(event:MouseEvent)
{
if (drawing)
{
//checkIt();
myshape.graphics.lineTo(mouseX,mouseY);
if (myshape.hitTestPoint(theBall.x,theBall.y, true))
{
trace("Hit A WALL!");
myshape.graphics.clear();
myshape.graphics.lineStyle(12, 0xFFFFFF);
myshape.graphics.moveTo(mouseX,mouseY);
}
}
}
public function stopDrawing(event:MouseEvent)
{
drawing = false;
}
}
}
Another option is to test the colour of the map bitmapdata pixel that corresponds to the "player's position" (the end of the drawn line, in this case):
var testPixel:uint = _myBitmapData.getPixel(xPosition, yPosition);
Or you can use .getPixel32 which includes alpha in the returned uint.
I FOUND A WORKING SOLUTION:
I found a working solution thanks to fsbmain. Thank you. I am posting my full code in hopes that this can help someone else.
In the end I had to use another movieClip rather than the mouse, but this worked for me. Now instead of drawing anywhere in the maze they have to drag a little character named Beau thru the maze. This works better for me.
It would be nice to know how to also detect if the mouse or the actual line I am drawing hit the wall as well. Maybe someone can make a suggestion. Nevertheless, thanks for helping me get this far.
The short and essential code to make my movieClip detect the alpha can be found here. It really is very short compared to other complicated options I found. Here is the link: http://www.mikechambers.com/blog/2009/06/24/using-bitmapdata-hittest-for-collision-detection/
package
{
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.display.DisplayObject;
import flash.display.Graphics;
import flash.display.JointStyle;
import flash.display.LineScaleMode;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.*;
import flash.events.KeyboardEvent;
import flash.ui.Keyboard;
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.desktop.NativeApplication;
import flash.system.Capabilities;
import flash.display.*;
import flash.geom.*;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Matrix;
public class MazeClass extends Sprite
{
//Are we drawing or not?
private var drawing:Boolean;
public var myshape:Shape;
public var alreadyDrawn:Shape;
public var theMap:*;
public var swiper:Swiper = new Swiper();
public var Beau:littleBeau = new littleBeau();
//alreadyDrawn = new Shape();
public var currentGalleryItem:Number = 1;
public var totalGalleryItems:Number = 4;
public var redClipBmpData:BitmapData;
public var blueClipBmpData:BitmapData;
public var redRect:Rectangle;
public var blueRect:Rectangle;
public function MazeClass()
{
if (stage)
{
theMap = new MapOne();
myshape = new Shape();
myshape.graphics.lineStyle(33,0x0aa6df);
addChild(myshape);
drawing = false;//to start with
stage.addEventListener(MouseEvent.MOUSE_DOWN, startDrawing);
stage.addEventListener(MouseEvent.MOUSE_MOVE, draw);
stage.addEventListener(MouseEvent.MOUSE_UP, stopDrawing);
//stage.addEventListener(Event.ENTER_FRAME, checkIt);
stage.addEventListener(KeyboardEvent.KEY_UP, fl_OptionsMenuHandler);
Multitouch.inputMode = MultitouchInputMode.GESTURE;
addChild(theMap);
//theMap.height = stage.stageHeight - 200;
theMap.theStart.alpha = 0;
theMap.theFinish.alpha = 0;
addChild(swiper);
swiper.y = stage.stageHeight - swiper.height;
swiper.addEventListener(TransformGestureEvent.GESTURE_SWIPE, fl_SwipeToGoToNextPreviousFrame);
addChild(Beau);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
Beau.addEventListener(MouseEvent.MOUSE_DOWN, BeauStartDrag);
Beau.addEventListener(MouseEvent.MOUSE_UP, BeauStopDrag);
redRect = theMap.getBounds(this);
redClipBmpData = new BitmapData(redRect.width,redRect.height,true,0);
redClipBmpData.draw(theMap);
blueRect = Beau.getBounds(this);
blueClipBmpData = new BitmapData(blueRect.width,blueRect.height,true,0);
blueClipBmpData.draw(Beau);
//blueClipBmpData.x = theMap.theStart.x;
//blueClipBmpData.y = theMap.theStart.y - swiper.height;
stage.addEventListener(Event.ENTER_FRAME, enterFrame);
}
}
public function enterFrame(e:Event):void
{
//Beau.x = mouseX;
//Beau.y = mouseY;
if (redClipBmpData.hitTest(new Point(theMap.x, theMap.y),
255,
blueClipBmpData,
new Point(Beau.x, Beau.y),
255
))
{
trace("hit");
clearAll();
//redClip.filters = [new GlowFilter()];
}
else
{
trace("No Hit");
}
}
public function BeauStartDrag(event:MouseEvent):void
{
Beau.startDrag();
drawing = true;
}
public function BeauStopDrag(event:MouseEvent):void
{
drawing = false;
Beau.stopDrag();
}
public function startDrawing(event:MouseEvent):void
{
myshape.graphics.moveTo( mouseX, mouseY);
}
//drawing = true;
public function draw(event:MouseEvent)
{
if (drawing)
{
//checkIt();
myshape.graphics.lineTo(mouseX,mouseY);
}
}
public function stopDrawing(event:MouseEvent)
{
//drawing = false;
}
public function fl_OptionsMenuHandler(event:KeyboardEvent):void
{
if ((event.keyCode == 95) || (event.keyCode == Keyboard.MENU))
{
NativeApplication.nativeApplication.exit(0);
}
}
public function clearAll()
{
myshape.graphics.clear();
myshape.graphics.lineStyle(12, 0x0aa6df);
myshape.graphics.moveTo(mouseX,mouseY);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
drawing = false;
Beau.stopDrag();
}
public function fl_SwipeToGoToNextPreviousFrame(event:TransformGestureEvent):void
{
if (event.offsetX == 1)
{
if (currentGalleryItem > 1)
{
currentGalleryItem--;
trace("swipe Right");
clearAll();
removeChild(theMap);
theMap = new MapOne();
addChild(theMap);
theMap.height = stage.stageHeight - 200;
theMap.theStart.alpha = 0;
theMap.theFinish.alpha = 0;
addChild(Beau);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
}
}
else if (event.offsetX == -1)
{
if (currentGalleryItem < totalGalleryItems)
{
currentGalleryItem++;
trace("swipe Left");
clearAll();
removeChild(theMap);
theMap = new MapTwo();
addChild(theMap);
theMap.height = stage.stageHeight - 200;
theMap.theStart.alpha = 0;
theMap.theFinish.alpha = 0;
addChild(Beau);
Beau.x = theMap.theStart.x;
Beau.y = theMap.theStart.y - swiper.height;
}
}
}
}
}

How to call one of the function from this class?

I wanna call the function "nextMenu" & "prevMenu" from this class from Main.as
But I get the error 1136: Incorrect number of arguments. Expected 1.
Can help me see what I've left out on the codes?
CategoryScroller.as
package com.theflashfactor.carouselStackGallery.categoryMenu
{
import com.greensock.TweenMax;
import com.greensock.easing.Quint;
import com.theflashfactor.utils.Ref;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
/**
* Scroller to switch view for category item if there are more than visibleItem available
* #author Rimmon Trieu
*/
public class CategoryScroller extends Sprite
{
private var trackLength:int = 400;
private var scrubber:Sprite;
private var track:Shape;
private var categoryMenu:CategoryMenu;
private var trans:Sprite;
private var center:Number;
public function CategoryScroller(categoryMenu:CategoryMenu)
{
this.categoryMenu = categoryMenu;
buttonMode = true;
initialize();
}
/**
* Draw elemnt scrubber and track
*/
private function initialize():void
{
trans = new Sprite();
trans.graphics.beginFill(0, 0);
trans.graphics.drawRect(0, 0, trackLength, 13);
trans.graphics.endFill();
trans.addEventListener(MouseEvent.MOUSE_DOWN, transMouseDown, false, 0, true);
addChild(trans);
// Draw track
var color:uint = uint(Ref.getInstance().getRef("categoryCircleColor"));
track = new Shape();
track.graphics.lineStyle(1, color);
track.graphics.lineTo(trackLength, 0);
track.y = 6;
addChild(track);
// Draw scrubber
scrubber = new Sprite();
scrubber.graphics.beginFill(color);
scrubber.graphics.drawRect(0, 0, 80, 13);
scrubber.graphics.endFill();
center = (trackLength - scrubber.width) >> 1;
scrubber.x = center;
addChild(scrubber);
// Add dragging functionality
scrubber.addEventListener(MouseEvent.MOUSE_DOWN, scrubberMouseDown,false,0,true);
}
private function transMouseDown(event:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_UP, stageMouseUpHandler,false,0,true);
TweenMax.killTweensOf(scrubber);
categoryMenu.preTransition();
if (mouseX > width - scrubber.width) scrubber.x = (width - scrubber.width); else scrubber.x = mouseX;
}
/*private function transMouseUp(event:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, stageMouseUpHandler);
checkPosition();
}*/
private function scrubberMouseDown(event:MouseEvent):void
{
event.stopImmediatePropagation();
TweenMax.killTweensOf(scrubber);
scrubber.startDrag(false, new Rectangle(0, 0, trackLength - scrubber.width, 0));
stage.addEventListener(MouseEvent.MOUSE_UP, stageMouseUpHandler,false,0,true);
categoryMenu.preTransition();
}
private function stageMouseUpHandler(event:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, stageMouseUpHandler);
scrubber.stopDrag();
checkPosition();
}
private function checkPosition():void
{
var targetX:Number = (trackLength - scrubber.width) >> 1;
if (scrubber.x > (center + 20)) categoryMenu.postTransition(1);
else
if (scrubber.x < (center - 20)) categoryMenu.postTransition(-1);
else
categoryMenu.postTransition(0);
TweenMax.to(scrubber, .5, {x:targetX, ease:Quint.easeOut, overwrite:1});
}
public function nextMenu():void
{
categoryMenu.postTransition(1);
}
public function prevMenu():void
{
categoryMenu.postTransition(-1);
}
}
}
I've inserted the code below in my Main.as to call the function which I can't get it success.
import com.theflashfactor.carouselStackGallery.categoryMenu.CategoryScroller;
private var categoryScroller:CategoryScroller = new CategoryScroller();
categoryScroller.nextMenu();
Main.as
package
{
import com.theflashfactor.carouselStackGallery.CarouselStackGallery;
import com.theflashfactor.carouselStackGallery.categoryMenu.CategoryMenu;
import com.theflashfactor.carouselStackGallery.categoryMenu.CategoryScroller;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Rectangle;
import org.casalib.events.LoadEvent;
import org.casalib.load.DataLoad;
/**
* Main document class
* #author Rimmon Trieu
*/
[SWF(frameRate="60", backgroundColor="0", pageTitle="3D Carousel Stack Gallery")]
public class Main extends Sprite
{
private var xmlPath:String = "../xml/Main.xml";
private var ts3:Sprite = new Sprite;
private var categoryMenu:CategoryMenu = new CategoryMenu();
private var categoryScroller:CategoryScroller = new CategoryScroller();
public function Main()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
addEventListener(Event.ADDED_TO_STAGE, addToStage);
}
private function addToStage(event:Event):void
{
removeEventListener(Event.ADDED_TO_STAGE, addToStage);
var xmlLoad:DataLoad = new DataLoad(xmlPath);
xmlLoad.addEventListener(LoadEvent.COMPLETE, xmlLoaded);
xmlLoad.start();
ts3.graphics.beginFill(0x555555,1);
ts3.graphics.drawCircle(0, 0, 50);
ts3.graphics.endFill();
}
private function xmlLoaded(event:LoadEvent):void
{
event.target.removeEventListener(LoadEvent.COMPLETE, xmlLoaded);
opaqueBackground = uint(event.target.dataAsXml.settings.#backgroundColor);
var gallery:CarouselStackGallery = new CarouselStackGallery(event.target.dataAsXml);
addChild(gallery);
addChild(ts3);
ts3.addEventListener(MouseEvent.MOUSE_DOWN, ts3MouseDown,false,0,true);
}
private function ts3MouseDown(event:MouseEvent):void
{
categoryScroller.nextMenu();
}
}
}
As defined:
public function CategoryScroller(categoryMenu:CategoryMenu)
{
...
Shouldn't the class constructor be expecting an argument??
private var categoryScroller:CategoryScroller = new CategoryScroller();

AS3: Limiting the stage space of a function?

I want to know how to prevent the user from drawing outside my school board.
My board image sizes 709.15 X 499.5.
So I thought of something like this...
if(stage.stageWidth <= 709)
But if my board image is being called as a variable on stage boardActiva it should be easier.
Here's the function that draws:
private function dibujar(e:MouseEvent){
trace(e.localY);
tizaActiva.x = e.stageX;
tizaActiva.y = e.stageY;
if(dibujando){
tabla.graphics.lineTo(e.stageX,e.stageY);
}
And this is the full code:
package {
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.*;
import flash.trace.Trace;
import flash.ui.Mouse;
import flash.display.Shape;
import fl.controls.ColorPicker;
import fl.motion.Color;
import fl.events.ColorPickerEvent;
public class pizarra extends MovieClip {
private var colores:ColorPicker = new ColorPicker;
private var boardActiva:board = new board;
private var tizaActiva:tiza = new tiza();
private var tabla:Shape = new Shape;
private var dibujando:Boolean;
public function pizarra() {
Mouse.hide();
tabla.graphics.lineStyle(5,0xFFFFFF);
// constructor code
boardActiva.x = 45;
boardActiva.y = 40;
addChild(boardActiva);
addChild(tabla);
addChild(colores);
addChild(tizaActiva);
dibujando = false;
stage.addEventListener(MouseEvent.MOUSE_DOWN, empezarDibujo);
stage.addEventListener(MouseEvent.MOUSE_MOVE, dibujar);
stage.addEventListener(MouseEvent.MOUSE_UP, detenerDibujo);
colores.addEventListener(ColorPickerEvent.CHANGE,cambiar);
}
private function empezarDibujo(e:MouseEvent):void{
trace(e.localY);
tabla.graphics.moveTo(e.stageX,e.stageY);
dibujando = true;
}
private function dibujar(e:MouseEvent){
trace(e.localY);
tizaActiva.x = e.stageX;
tizaActiva.y = e.stageY;
if(dibujando){
tabla.graphics.lineTo(e.stageX,e.stageY);
}
}
private function detenerDibujo(e:MouseEvent){
trace(e.localY);
dibujando = false;
}
private function cambiar(e:ColorPickerEvent){
tabla.graphics.lineStyle(5,e.color);
}
}
}
If I understood correctly your question, this should do it:
private function dibujar(e:MouseEvent)
{
//trace(e.localY);
tizaActiva.x = e.stageX;
tizaActiva.y = e.stageY;
if(dibujando && insideBoard(e.stageX,e.stageY) )
{
tabla.graphics.lineTo(e.stageX,e.stageY);
}
}
private function insideBoard(x:Number,y:Number):Boolean
{
return ( (x>= boardActiva.x)
&& (x <= boardActiva.x + boardActiva.width )
&& (y >= boardActiva.y)
&& (y <= boardActiva.y + boardActiva.height ) );
}
Hope to be of some help, good luck with your pizarra ;)