AS3 MovieClip click event not working - actionscript-3

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

It probably has to do with the way you're drawing your MovieClips.
From the docs: "The opaque background region does not respond to mouse events."
Try drawing rectangles like this:
// SLIDER HOLDER
var canvas:MovieClip = new MovieClip();
canvas.graphics.beginFill(0xDDDDDD);
canvas.graphics.drawRoundRect(0, 0, this.stageWidth, this.stageHeight, 15, 15);
canvas.graphics.endFill();
canvas.mouseEnabled = true;
this.STAGE.addChild(canvas);

You need to add Event after slider added to stage so in the slider class you need to write
package {
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.Event;
import flash.events.MouseEvent;
public class Slider extends MovieClip {
private var images:Array;
private var STAGE:Stage;
private var stageWidth:Number;
private var stageHeight:Number;
private var centerX:Number;
private var centerY:Number;
private var tsHeight:Number = 100;
private var tsPadding:Number = 10;
public function Slider(stageGlobal, imageConfig:Array) {
this.STAGE = stageGlobal;
this.images = imageConfig;
this.addEventListener(Event.ADDED_TO_STAGE, added);
}
public function added(e:Event)
{
this.stageWidth = this.STAGE.stageWidth;
this.stageHeight = this.STAGE.stageHeight;
this.centerX = this.stageWidth / 2;
this.centerY = this.stageHeight / 2;
this.createCanvas();
}
public function createCanvas():void {
// SLIDER HOLDER
var canvas:MovieClip = new MovieClip();
canvas.graphics.drawRoundRect(0, 0, this.stageWidth, this.stageHeight, 15, 15);
canvas.opaqueBackground = 0xDDDDDD;
canvas.mouseEnabled = true;
this.STAGE.addChild(canvas);
// HEADER / TITLE HOLDER
var header:MovieClip = new MovieClip();
header.graphics.drawRoundRect(0, 0, this.stageWidth, 40, 15, 15);
header.opaqueBackground = 0x000000;
canvas.addChild(header);
// FOOTER ACTION HOLDER
var footer:MovieClip = new MovieClip();
footer.graphics.drawRoundRect(0, this.stageHeight - 40, this.stageWidth, 40, 15, 15);
footer.opaqueBackground = 0x000000;
canvas.addChild(footer);
// THUMBSTRIP HOLDER
var thumbstrip:MovieClip = new MovieClip();
thumbstrip.graphics.drawRoundRect(0, this.stageHeight - 160, this.stageWidth, 120, 15, 15);
thumbstrip.opaqueBackground = 0x555555;
canvas.addChild(thumbstrip);
canvas.addEventListener(MouseEvent.CLICK, canvasClick);
}
private function canvasClick(e:MouseEvent):void {
trace(e);
}
}
}
I hope it would help :)

Related

Duplicating video Stream Actionscript 3

Good Morning,
i am working on a video class, using a CRTMP Server for streaming. This works fine, but for my solution i need to duplicate the video stream (for some effects).
I googled for duplicate MovieClips and tried to duplicate the video like this.
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.media.*;
import flash.system.*;
import flash.utils.ByteArray;
public class Main extends MovieClip
{
public var netStreamObj:NetStream;
public var nc:NetConnection;
public var vid:Video;
public var vid2:Video;
public var streamID:String;
public var videoURL:String;
public var metaListener:Object;
public function Main()
{
init_RTMP();
}
private function init_RTMP():void
{
streamID = "szene3.f4v";
videoURL = "rtmp://213.136.73.230/maya";
vid = new Video(); //typo! was "vid = new video();"
vid2 = new Video();
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.client = {onBWDone: function():void
{
}};
nc.connect(videoURL);
}
private function onConnectionStatus(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
trace("Creating NetStream");
netStreamObj = new NetStream(nc);
metaListener = new Object();
metaListener.onMetaData = received_Meta;
netStreamObj.client = metaListener;
netStreamObj.play(streamID);
vid.attachNetStream(netStreamObj);
//vid2.attachNetStream(netStreamObj); // wont work
addChild(vid);
// addChild(vid2); // wont work either
//intervalID = setInterval(playback, 1000);
}
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace("asyncErrorHandler.." + "\r");
}
private function received_Meta(data:Object):void
{
var _stageW:int = stage.stageWidth;
var _stageH:int = stage.stageHeight;
var _videoW:int;
var _videoH:int;
var _aspectH:int;
var Aspect_num:Number; //should be an "int" but that gives blank picture with sound
Aspect_num = data.width / data.height;
//Aspect ratio calculated here..
_videoW = _stageW;
_videoH = _videoW / Aspect_num;
_aspectH = (_stageH - _videoH) / 2;
vid.x = 0;
vid.y = _aspectH;
vid.width = _videoW;
vid.height = _videoH;
vid2.x = 0;
vid2.y = _aspectH ;
}
}
It should be possible to duplicate the video stream. 2 Instance of the same videoStream. What am i doing wrong ?
Thanks for help.
"This means that i have to double the netstream. This is not what i want."
"I tried to duplicate the video per Bitmap.clone. But i got an sandbox violation."
You can try the workaround suggested here: Netstream Play(null) Bitmapdata Workaround
I'll show a quick demo of how it can be applied to your code.
This demo code assumes your canvas is width=550 & height=400. Keep that ratio if scaling up.
package
{
import flash.display.*;
import flash.events.*;
import flash.net.*;
import flash.media.*;
import flash.system.*;
import flash.utils.ByteArray;
import flash.geom.*;
import flash.filters.ColorMatrixFilter;
public class Main extends MovieClip
{
public var netStreamObj:NetStream;
public var nc:NetConnection;
public var vid:Video;
public var streamID:String;
public var videoURL:String;
public var metaListener:Object;
public var vid1_sprite : Sprite = new Sprite();
public var vid2_sprite : Sprite = new Sprite();
public var vid2_BMP : Bitmap;
public var vid2_BMD : BitmapData;
public var colMtx:Array = new Array(); //for ColorMatrix effects
public var CMfilter:ColorMatrixFilter;
public function Main()
{
init_RTMP();
}
private function init_RTMP():void
{
streamID = "szene3.f4v";
videoURL = "rtmp://213.136.73.230/maya";
vid = new Video();
nc = new NetConnection();
nc.addEventListener(NetStatusEvent.NET_STATUS, onConnectionStatus);
nc.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
nc.client = { onBWDone: function():void { } };
//nc.connect(null); //for file playback
nc.connect(videoURL); //for RTMP streams
}
private function onConnectionStatus(e:NetStatusEvent):void
{
if (e.info.code == "NetConnection.Connect.Success")
{
trace("Creating NetStream");
netStreamObj = new NetStream(nc);
metaListener = new Object();
metaListener.onMetaData = received_Meta;
netStreamObj.client = metaListener;
//netStreamObj.play("vid.flv"); //if File
netStreamObj.play(streamID); //if RTMP
vid.attachNetStream(netStreamObj);
}
}
private function asyncErrorHandler(event:AsyncErrorEvent):void
{
trace("asyncErrorHandler.." + "\r");
}
private function received_Meta(data:Object):void
{
trace("Getting metadata");
var _stageW:int = stage.stageWidth;
var _stageH:int = stage.stageHeight;
var _videoW:int = data.width;
var _videoH:int = data.height;
var _aspectH:int = 0;
var Aspect_num:Number;
Aspect_num = data.width / data.height;
//Aspect ratio calculated here..
_videoW = _stageW;
_videoH = _videoW / Aspect_num;
_aspectH = (_stageH - _videoH) / 2;
trace("_videoW : " + _videoW);
trace("_videoW : " + _videoH);
trace("_aspectH : " + _aspectH);
vid.x = 0;
vid.y = 0;
vid.width = _videoW;
vid.height = _videoH;
setup_Copy(); //# Do this after video resize
}
public function setup_Copy () : void
{
vid2_BMD = new BitmapData(vid.width, vid.height, false, 0);
vid2_BMP = new Bitmap( vid2_BMD );
vid1_sprite.addChild(vid);
vid1_sprite.x = 0;
vid1_sprite.y = 0;
addChild( vid1_sprite );
vid2_sprite.addChild( vid2_BMP );
vid2_sprite.x = 0;
vid2_sprite.y = vid.height + 5;
addChild( vid2_sprite );
stage.addEventListener(Event.ENTER_FRAME, draw_Video);
}
public function draw_Video (evt:Event) : void
{
if ( netStreamObj.client.decodedFrames == netStreamObj.decodedFrames ) { return; } // Here we skip multiple readings
//# Get bitmapdata directly from container of video
if ( vid1_sprite.graphics.readGraphicsData().length > 0 )
{
vid2_BMD = GraphicsBitmapFill(vid1_sprite.graphics.readGraphicsData()[0]).bitmapData;
}
effect_BitmapData(); //# Do an effect to bitmapdata
}
public function effect_BitmapData ( ) : void
{
//# Matrix for Black & White effect
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // red
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // green
colMtx = colMtx.concat([1/3, 1/3, 1/3, 0, 0]); // blue
colMtx = colMtx.concat([0, 0, 0, 1, 0]); // alpha
CMfilter = new ColorMatrixFilter(colMtx);
vid2_BMP.bitmapData.applyFilter(vid2_BMD, new Rectangle(0, 0, vid.width, vid.height), new Point(0, 0), CMfilter);
}
}
}

Simplebutton image is larger than it actually is

I'm creating a button I use beginBitmapFill method to add image to it. Everything works normally, the problem is that the image loaded by a Loader () is greater than it actually is
Class that creates the button
package mode {
import flash.display.Sprite;
import org.osmf.net.StreamingURLResource;
public class LoadButton extends Sprite
{
public var Save;
public function LoadButton(x:uint,save:String,url:String)
{
var button:CustomSimpleButton = new CustomSimpleButton(url);
button.x = x;
Save = save;
addChild(button);
}
}
}
import flash.display.*;
import flash.display.Bitmap;
import flash.display.DisplayObject;
import flash.display.Shape;
import flash.display.SimpleButton;
import flash.events.*;
import flash.events.EventDispatcher;
import flash.events.MouseEvent;
import flash.net.URLRequest;
import flash.geom.Matrix;
class CustomSimpleButton extends SimpleButton
{
private var upColor:uint = 0xFFCC00;
private var overColor:uint = 0xCCFF00;
private var downColor:uint = 0x00CCFF;
private var sizew:uint = 100;
private var sizeh:uint = 88;
public function CustomSimpleButton(url:String)
{
downState = new ButtonDisplayState(downColor, sizew,sizeh,url);
overState = new ButtonDisplayState(overColor, sizew,sizeh,url);
upState = new ButtonDisplayState(upColor, sizew,sizeh,url);
hitTestState = new ButtonDisplayState(upColor, sizew * 2,sizeh,url);
hitTestState.x = -(sizew / 4);
hitTestState.y = hitTestState.x;
useHandCursor = true;
}
}
class ButtonDisplayState extends Shape
{
private var bgColor:uint;
private var size:uint;
private var sizeh:uint;
public function ButtonDisplayState(bgColor:uint, sizew:uint,sizeh:uint,url:String)
{
this.bgColor = bgColor;
this.size = sizew;
this.sizeh = sizeh;
draw(url);
}
private function draw(url:String):void
{
var myLoader:Loader = new Loader();
var image:Bitmap;
var uri = new URLRequest(url);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event)
{
image = new Bitmap(e.target.content.bitmapData);
graphics.beginBitmapFill(image.bitmapData);
graphics.drawRect(0, 0, 100, 88);
graphics.endFill();
});
myLoader.load(uri);
}
}
How the image is 100x88
as it is
The reason it is showing up cropped like that, is because the BitmapData is larger than the area you are filling.
Before filling the shape with the loaded BitmapData, you need to sale it down to the appropriate size.
Based on the answer to this question, you could do the following:
var scaleAmount:Number;
if(e.target.content.width >= e.target.content.height){
scaleAmount = size / e.target.content.width;
}else{
scaleAmount = sizeh / e.target.content.height;
}
var scaledBitmapData:BitmapData = scaleBitmapData(e.target.content.bitmapData, scaleAmount);
graphics.beginBitmapFill(scaledBitmapData);
graphics.drawRect(0, 0, size, sizeh);
graphics.endFill();
function scaleBitmapData(bitmapData:BitmapData, scale:Number):BitmapData {
scale = Math.abs(scale);
var width:int = (bitmapData.width * scale) || 1;
var height:int = (bitmapData.height * scale) || 1;
var transparent:Boolean = bitmapData.transparent;
var result:BitmapData = new BitmapData(width, height, transparent);
var matrix:Matrix = new Matrix();
matrix.scale(scale, scale);
result.draw(bitmapData, matrix);
return result;
}
It might be easier though, to just make your button state a Sprite and add the loaded Bitmap object and scale it directly:
class ButtonDisplayState extends Sprite
{
private var bgColor:uint;
private var image:Bitmap;
private var size:uint;
private var sizeh:uint;
public function ButtonDisplayState(bgColor:uint, sizew:uint,sizeh:uint,url:String)
{
this.bgColor = bgColor;
this.size = sizew;
this.sizeh = sizeh;
loadImage(url);
}
private function loadImage(url:String):void
{
var myLoader:Loader = new Loader();
var uri = new URLRequest(url);
myLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e:Event)
{
image = new Bitmap(e.target.content.bitmapData);
//scale the bitmap while retaining aspect ratio
//scale based off which dimension (width or height) is bigger
if(image.width >= image.height){
image.scaleX= size / image.width; //scale it to the width specified
image.scaleY = image.scaleX; //make the height aspect ratio match the widths
}else{
image.scaleY = sizeh /image.height;
image.scaleX = image.scaleY;
}
addChild(image); //add it to the display list of this object
});
myLoader.load(uri);
}
}

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

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

AS3.0 Augmented Reality 1046 Error

I am having an Error on the loop function can anyone tell me what i am doing wrong?
I think my syntax is good?
Severity and Description Path Resource Location Creation Time Id
1046: Type was not found or was not a compile-time constant: Event. ar/src ar.as line 94 1318225764229 228
package {
import flash.display.Sprite;
import org.papervision3d.objects.primitives.Cube;
[SWF(width="640", height="480", framerate="30", backgroundColor="#ffffff")]
public class ar extends Sprite
{
// Embed the marker.pat file
[Embed(source="marker.pat", mimeType="application/octet-stream")]
private var marker:Class;
// Embed the camera.pat file
[Embed(source="camera_para.dat", mimeType="application/octet-stream")]
private var cam_params:Class;
// createFLAR Vars
private var ar_params:FLARParam;
private var ar_marker:FLARCode;
// createCAM Vars
private var ar_vid:Video;
private var ar_cam:Camera;
// createBMP Vars
private var ar_bmp:BitmapData;
private var ar_raster:FLARRgbRaster_BitmapData;
private var ar_detection:FLARSingleMarkerDetector;
// createPapervision Vars
private var ar_scene:Scene3D;
private var ar_3dcam:FLARCamera3D;
private var ar_basenode:FLARBaseNode;
private var ar_viewport:Viewport3D;
private var ar_renderengine:BasicRenderEngine;
private var ar_transmat:FLARTransMatResult;
private var ar_cube:Cube;
public function ARProj()
{
createFLAR();
createCAM();
createBMP();
createPapervision();
addEventListener(Event.ENTER_FRAME, loop);
}
public function createFLAR()
{
ar_params = new FLARParam();
ar_marker = new FLARCode();
ar_params.loadParam(new cam_params() as ByteArray);
ar_marker.loadARPatt(new marker());
}
public function createCAM()
{
ar_vid = new Video(640, 480);
ar_cam = Camera.getCamera();
ar_cam.setMode(640,480,30);
ar_vid.attachCamera(ar_cam);
addChild(ar_vid);
}
public function createBMP()
{
ar_bmp = new BitmapData(640,480);
ar_bmp.draw(ar_vid);
ar_raster = new FLARRgbRaster_BitmapData(ar_bmp);
ar_raster = new FLARSingleMarkerDetector(ar_params, ar_marker, 80);
}
public function createPapervision()
{
ar_scene = new Scene3D();
ar_3dcam = new FLARCamera3D(ar_params);
ar_basenode = new FLARBaseNode();
ar_renderengine = new BasicRenderEngine();
ar_transmat = new FLARTransMatResult();
ar_viewport = new Viewport3D();
var ar_light:PointLight3D = new PointLight3D();
ar_light.x = 1000;
ar_light.y = 1000;
ar_light.z = -1000;
var ar_bitmap:BitmapMaterial;
ar_bitmap = new BitmapFileMaterial("image.jpeg");
ar_bitmap.doubleSided = true;
ar_cube = new Cube(new MaterialsList({all:ar_bitmap}), 80, 80, 80);
ar_scene.addChild(ar_baseNnode);
ar_basenode.addChild(ar_cube);
addChild(ar_viewport);
}
public function loop(e:Event):void
{
ar_bmp.draw(ar_vid);
ar_cube.rotationX +=4;
ar_cube.rotationY +=6;
try
{
if (ar_detection.detectMarkerLite(ar_raster, 80) && ar_detection.getConfidence() > 0)
{
ar_detection.getTransformMatrix(ar_transmat);
ar_basenode.setTransformMatrix(ar_transmat);
ar_renderengine.renderScene(ar_scene, ar_3dcam, ar_viewport);
}
}
catch(e:Error){
}
}
}
}
import flash.events.Event;
You have not imported Event class. Add this import.
You're missing the import for the event Class (and probably more).

3D object in FLARToolKit keep appearing even though there is no marker detected

I have another (newbie) question about FLARToolKit.
This is Lee Brimelow's code to make 3 boxes on top of the marker.
package {
import flash.display.BitmapData;
import flash.display.Sprite;
import flash.events.Event;
import flash.media.Camera;
import flash.media.Video;
import flash.utils.ByteArray;
import org.libspark.flartoolkit.core.FLARCode;
import org.libspark.flartoolkit.core.param.FLARParam;
import org.libspark.flartoolkit.core.raster.rgb.FLARRgbRaster_BitmapData;
import org.libspark.flartoolkit.core.transmat.FLARTransMatResult;
import org.libspark.flartoolkit.detector.FLARSingleMarkerDetector;
import org.libspark.flartoolkit.support.pv3d.FLARBaseNode;
import org.libspark.flartoolkit.support.pv3d.FLARCamera3D;
import org.papervision3d.lights.PointLight3D;
import org.papervision3d.materials.shadematerials.FlatShadeMaterial;
import org.papervision3d.materials.utils.MaterialsList;
import org.papervision3d.objects.primitives.Cube;
import org.papervision3d.render.BasicRenderEngine;
import org.papervision3d.scenes.Scene3D;
import org.papervision3d.view.Viewport3D;
[SWF(width="640", height="480", frameRate="30", backgroundColor="#FFFFFF")]
public class FLARdemo extends Sprite
{
[Embed(source="pat1.pat", mimeType="application/octet-stream")]
private var pattern:Class;
[Embed(source="camera_para.dat", mimeType="application/octet-stream")]
private var params:Class;
private var fparams:FLARParam;
private var mpattern:FLARCode;
private var vid:Video;
private var cam:Camera;
private var bmd:BitmapData;
private var raster:FLARRgbRaster_BitmapData;
private var detector:FLARSingleMarkerDetector;
private var scene:Scene3D;
private var camera:FLARCamera3D;
private var container:FLARBaseNode;
private var vp:Viewport3D;
private var bre:BasicRenderEngine;
private var trans:FLARTransMatResult;
public function FLARdemo()
{
setupFLAR();
setupCamera();
setupBitmap();
setupPV3D();
addEventListener(Event.ENTER_FRAME, loop);
}
private function setupFLAR():void
{
fparams = new FLARParam();
fparams.loadARParam(new params() as ByteArray);
mpattern = new FLARCode(16, 16);
mpattern.loadARPatt(new pattern());
}
private function setupCamera():void
{
vid = new Video(640, 480);
cam = Camera.getCamera();
cam.setMode(640, 480, 30);
vid.attachCamera(cam);
addChild(vid);
}
private function setupBitmap():void
{
bmd = new BitmapData(640, 480);
bmd.draw(vid);
raster = new FLARRgbRaster_BitmapData(bmd);
detector = new FLARSingleMarkerDetector(fparams, mpattern, 80);
}
private function setupPV3D():void
{
scene = new Scene3D();
camera = new FLARCamera3D(fparams);
container = new FLARBaseNode();
scene.addChild(container);
var pl:PointLight3D = new PointLight3D();
pl.x = 1000;
pl.y = 1000;
pl.z = -1000;
var ml:MaterialsList = new MaterialsList({all: new FlatShadeMaterial(pl)});
var Cube1:Cube = new Cube(ml, 30, 30, 30);
var Cube2:Cube = new Cube(ml, 30, 30, 30);
Cube2.z = 50
var Cube3:Cube = new Cube(ml, 30, 30, 30);
Cube3.z = 100
container.addChild(Cube1);
container.addChild(Cube2);
container.addChild(Cube3);
bre = new BasicRenderEngine();
trans = new FLARTransMatResult();
vp = new Viewport3D;
addChild(vp);
}
private function loop(e:Event):void
{
bmd.draw(vid);
try
{
if(detector.detectMarkerLite(raster, 80) && detector.getConfidence() > 0.5)
{
detector.getTransformMatrix(trans);
container.setTransformMatrix(trans);
bre.renderScene(scene, camera, vp);
}
}
catch(e:Error){}
}
}
the flaw of this code is, after the marker detected, yes, the 3D object got rendered. but after the marker were not detected, the object still appeared on the screen (even though it did not move)
how can I fix this?
you have to change the visible property of the FLARBaseNode in the detection condition
if(detector.detectMarkerLite(raster, 80) && detector.getConfidence() > 0.5){
detector.getTransformMatrix(trans);
container.setTransformMatrix(trans);
container.visible = true;
bre.renderScene(scene, camera, vp);
}else
container.visible = false;