What's wrong with my animation function? - apache-flex

It animates but it put's the piece of the sprite sheet where it is on the sprite sheet and not where the x and y tell it to. It's very short, so please take a look? Thank you in advance.
package cyanprime{
import flash.display.*;
import flash.geom.Rectangle;
public class Player{
[Embed(source="brownplane.png")]
public var image:Class;
public var bitmapdata:BitmapData = getBitmap(new image());
public var bitmap:Bitmap = new Bitmap(bitmapdata);
public var speed:int = 5;
public var x:int = 50;
public var y:int = 50;
public var frame:int = 0;
public function getBitmap(img:DisplayObject):BitmapData{
var drawRect:Rectangle = new Rectangle((img.width/3) * frame, 0, img.width/3, img.height);
var bitmap:BitmapData = new BitmapData(img.width, img.height);
bitmap.draw(img,null,null,null,drawRect);
return bitmap;
}
public function animate():void{
bitmap.bitmapData = getBitmap(new image());
frame++;
if(frame > 2)
frame = 0;
bitmap.x = x;
bitmap.y = y;
}
}
}

Looks like you need to add a matrix transform to draw() to translate the position of the rectangle being drawn. Something like this:
var trans:Matrix = new Matrix();
trans.tx = drawRect.x;
bitmap.draw(img,trans,null,null,drawRect);
If that doesn't work, try -drawRect.x, I can't exactly remember how that transform is applied.

Related

dispatch event not fired in action script 2.0

I have created a class named CheckBoxSelectAll in which I am triggering an event as below.
import mx.events.EventDispatcher;
import flash.filters.GlowFilter;
class CheckBoxSelectAll
{
public function dispatchEvent() {};
public function addEventListener() {};
public function removeEventListener() {};
private var checkbox_mc:MovieClip;
private var parent_mc:MovieClip;
function CheckBoxSelectAll()
{
mx.events.EventDispatcher.initialize(this);
}
function CreateCheckBox(c_mc:MovieClip)
{
var labelGlow:GlowFilter = new GlowFilter(0xFFFFFF, .30, 4, 4, 3, 3);
var labelFilters:Array = [labelGlow];
this.parent_mc = c_mc;
checkbox_mc = parent_mc.createEmptyMovieClip("",this.checkbox_mc.getNextHighestDepth() );
checkbox_mc._x =450;// boxX;
checkbox_mc._y =143;// boxY;
checkbox_mc.lineStyle(1, 0);
checkbox_mc.beginFill(currentFill, currentAlpha);
checkbox_mc.moveTo(0, triSize);
checkbox_mc.lineTo(triSize, triSize);
checkbox_mc.lineTo(triSize, 0);
checkbox_mc.lineTo(0, 0);
checkbox_mc.lineTo(0, triSize);
checkbox_mc.endFill();
checkbox_mc._visible = true;
checkbox_mc.onPress = function() {
var eventObject:Object = {target:this, type:'onDataReady'};
dispatchEvent(eventObject);
trace("OnPress refresh...");
}
}
}
In Parent movie clip, used following code
var select_all_listener:Object = new Object();
select_all_listener.onDataReady = triggerDisksLoad;
var select_all_box:CheckBoxSelectAll;
select_all_box = new CheckBoxSelectAll();
select_all_box.addEventListener("onDataReady", select_all_listener);
select_all_box.CreateCheckBox(this);
function triggerDisksLoad(evtObj) { trace("triggerDisksLoad called...!!!"); }
Here function triggerDisksLoad is not called.
The problem of your code is the scope where the checkbox_mc.onPress handler is executed, to avoid that, you can use the Delegate class, like this :
import mx.events.EventDispatcher;
import mx.utils.Delegate;
class CheckBoxSelectAll extends MovieClip
{
// ...
function CreateCheckBox(c_mc:MovieClip)
{
// ...
checkbox_mc.onPress = Delegate.create(this, _onPress);
}
private function _onPress():Void {
var event:Object = {target: this, type: 'onDataReady'};
dispatchEvent(event);
}
}
Also for the new MovieClips creation, when we use getNextHighestDepth(), it's usually used with the parent of the new MovieClip, so you can write :
checkbox_mc = parent_mc.createEmptyMovieClip('mc_name', parent_mc.getNextHighestDepth());
Hope that can help.

How can I take a screen shot of entire Screen on regular intervals using Adobe flex and action script

How can I take screen shot of Entire on Screen regular intervals (random between 2 to 5 minutes) without click event using Adobe flex and action script. Currently I am doing it with the Mouse_Up Event and then calling the timer and then saving each image with different name
package
{
import flash.desktop.NativeProcess;
import flash.desktop.NativeProcessStartupInfo;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageDisplayState;
import flash.display.StageScaleMode;
import flash.events.MouseEvent;
import flash.events.NativeProcessExitEvent;
import flash.events.TimerEvent;
import flash.filesystem.File;
import flash.system.Capabilities;
import flash.utils.Timer;
public class Grabber extends Sprite
{
private var stageCover:Sprite;
private var captureRect:Sprite;
private var sx:Number;
private var sy:Number;
private var np:NativeProcess;
private var npi:NativeProcessStartupInfo;
public function Grabber()
{
super();
stage.displayState = StageDisplayState.FULL_SCREEN_INTERACTIVE;
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
stageCover = new Sprite();
stageCover.graphics.beginFill(0xFFFFFF, 0.01);
stageCover.graphics.drawRect(0, 0, Capabilities.screenResolutionX, Capabilities.screenResolutionY);
addChild(stageCover);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
captureRect = new Sprite();
captureRect.graphics.lineStyle(2, 0xFFFFFF);
addChild(captureRect);
np = new NativeProcess();
npi = new NativeProcessStartupInfo();
}
private function onTimerComplete( event:TimerEvent):void
{
captureRect.graphics.clear();
var args:Vector.<String> = new Vector.<String>();
args.push("-l");
sx =0;
args.push(sx.toString());
args.push("-t");
sy = 0 ;
args.push(sy.toString());
args.push("-r");
var a:Number = Capabilities.screenResolutionX;
args.push(a.toString());
args.push("-b");
var b:Number= Capabilities.screenResolutionY;
args.push(b.toString());
args.push("-out");
args.push(File.desktopDirectory.nativePath + "/grab.jpeg");
npi.arguments = args;
npi.executable = File.applicationDirectory.resolvePath("GrabberCommand.exe");
np.start(npi);
}
private function onMouseUp(event:MouseEvent):void
{
var timer:Timer=new Timer( 10*1000*Math.random(),1 );
timer.addEventListener( TimerEvent.TIMER, onTimerComplete );
timer.start();
}
}
}
XML Properties are
SystemChrome none
Transparent true
SupportedProfiles extendedDesktop
I actually did something like this before.
You will need a Timer that calls the following function at intervals (whatever intervals you like):
private function captureScreenshots(event:MouseEvent):void
{
var imgEnc:IImageEncoder;
var screenshotArray:Array = new Array();
if(myView.encodingCombo.selectedItem == "PNG")
{
imgEnc = pngEnc; //private const pngEnc:PNGEncoder = new PNGEncoder();
}
else
{
imgEnc = jpgEnc; //private const jpgEnc:JPEGEncoder = new JPEGEncoder();
}
var windowsArray:Array = NativeApplication.nativeApplication.openedWindows;
for each(var window:NativeWindow in windowsArray)
{
if(window && window.stage is IBitmapDrawable)
{
var imageSnapshot:ImageSnapshot = ImageSnapshot.captureImage(window.stage as IBitmapDrawable, 0, imgEnc);
screenshotArray.push(imageSnapshot);
}
}
windowsArray = null;
}
You can then use a FileStream to write them to a directory, but that would be a different question.

Need soution for equalizer in flex?

I have developed a small application for testing 5 band equalizer in flex. I found the code in this link Flex Equalizer
The equalizer works fine.But i am not able to seek the desired position while playing the mp3 file.Following is my code....How to solve this problem?
import __AS3__.vec.Vector;
import mx.events.FlexEvent;
import spark.components.VSlider;
public static const BUFFER_SIZE:int = 8192;
public static const SAMPLE_RATE:int = 44100;
private var _Position:Number=0;
private var timer:Timer = new Timer(1000);
private const _soundURI:String = "testfile.mp3";
private var _out_snd:Sound = new Sound();
private const _eqL:EQ = new EQ();
private const _eqR:EQ = new EQ();
private var _loop_snd:Sound = new Sound();
// For storing dynamically created VSliders
private const _sliders_vect:Vector.<VSlider> = new Vector.<VSlider>();
private var _channel:SoundChannel = new SoundChannel();
private var _samples:ByteArray;
protected function view1_initializeHandler(event:FlexEvent):void
{
// TODO Auto-generated method stub
timer.addEventListener(TimerEvent.TIMER,timerFunction);
pgHolder.addEventListener(MouseEvent.CLICK,seekf);
setupEQ();
loadSound();
}
private function timerFunction(event:TimerEvent):void
{
_Position = _channel.position;
pgHolder.value=_Position;
}
private function seekf(event:MouseEvent):void
{
_channel.stop();
_Position = (pgHolder.contentMouseX/pgHolder.width)*_loop_snd.length;
startPlay();
}
private function loadSound():void
{
_Position=0;
_loop_snd.addEventListener(Event.COMPLETE, loadSoundComplete);
_loop_snd.addEventListener(IOErrorEvent.IO_ERROR, loadSoundError);
_out_snd.addEventListener(SampleDataEvent.SAMPLE_DATA, processSound);
_loop_snd.load(new URLRequest(_soundURI));
}
private function loadSoundComplete(event:Event):void
{
pgHolder.minimum=0;
pgHolder.maximum=_loop_snd.length;
timer.start();
startPlay();
}
private function startPlay():void
{
_channel=_out_snd.play(_Position);
}
private function loadSoundError(event:Event):void
{
trace("loadError");
}
// Create Sliders for changing EQ gain
private function setupEQ():void
{
var slider:VSlider;
for (var i:int = 0; i < _eqL.gains.length; i++) {
slider = new VSlider();
slider.x = (i * 35);
slider.y = 20;
slider.value = .9;
slider.maximum = 1;
slider.snapInterval=0.1;
slider.minimum = 0;
slider.addEventListener("change", changeEQHandler);
addElement(slider);
_sliders_vect[i] = slider;
}
var event:Event = new Event("change");
changeEQHandler(event);
}
private function processSound(event:SampleDataEvent):void
{
//trace("loading");
if(_Position>=_loop_snd.length)
{
_channel.stop();
}
_samples = new ByteArray();
var len:Number = _loop_snd.extract(_samples,BUFFER_SIZE);
var i:int=0;
var l:Number;
var r:Number;
if ( len < BUFFER_SIZE ) { // If end of MP3, start over
len += _loop_snd.extract(_samples,BUFFER_SIZE-len,0);
}
_samples.position = 0;
trace("len" + len + "//" + _channel.position + "//" +_samples.length);
while (i < BUFFER_SIZE) {
event.data.writeFloat(_eqL.compute(_samples.readFloat()));
event.data.writeFloat(_eqR.compute(_samples.readFloat()));
i++;
}
}
// Update EQ gains when sliders are changed
private function changeEQHandler(event:Event):void
{
var i:int = 0;
for(i = 0; i < _eqL.gains.length; i++){
_eqL.gains[i] = _sliders_vect[i].value * 2;
}
for(i = 0; i < _eqR.gains.length; i++){
_eqR.gains[i] = _sliders_vect[i].value * 2;
}
}
]]>
</fx:Script>
<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>
<s:HSlider width="100%" height="100%" id="pgHolder">
</s:HSlider>
When you handle the slider change, I see you calculate the new _Position, but _Position is not bindable and its never used set set the player position.
This is just pseudo-code, but shouldn't you do something like:
private function seekf(event:MouseEvent):void
{
_channel.stop();
_channel.position = (pgHolder.contentMouseX/pgHolder.width)*_loop_snd.length;
_channel.start();
}
Just looking at your code, when you set _Position = _channel.position, you are simply getting a value, not a reference. My guess is that you need to set _channel.position

What's wrong with this piece of code?

I'm trying to make a image editor in Flex 4.5.
However, there's one little thing that doesn't work as appropriate. Here's my code:
private function returnCropIndicatorBmpDataForTopLeft():BitmapData{
var topLeftX:int = 0;
var topLeftY:int = 0;
var topRightX:int = _bmpData.width;
var topRightY:int = 0;
var bottomRightX:int = _bmpData.width;
var bottomRightY:int = _bmpData.height;
var bottomLeftX:int = 0;
var bottomLeftY:int = _bmpData.height;
var cropIconX:int = _mouseX;
var cropIconY:int = _mouseY;
var temporaryBitmapData:BitmapData = _bmpData;
var originalColor:uint;
var dimmedColor:uint = 0x202020;
for (var i:int = 0; i < _bmpData.width; i++)
{
for (var j:int = 0; j < _bmpData.height; j++)
{
originalColor = _bmpData.getPixel(i,j);
if(i>cropIconX && j>cropIconY){
temporaryBitmapData.setPixel(i,j,originalColor);
}else{
temporaryBitmapData.setPixel(i,j,dimmedColor);
}
}
}
/*
*by the end of this loop, we have, in the temporaryBitmapData variable, a version of the _bmpData,
*the area to be cropped out dimmed a little bit.
*/
return temporaryBitmapData;
}
if you look carefully inside the first if statement in the innermost for loop,
temporaryBitmapData.setPixel(i,j,originalColor);
that bit of code should do the following:
If this (i,j) pixel is outside of the "to-be-cropped-out area", then repaint it with the original pixel color.
It just can't seem to get that to work!!!!
I've substituted that line with some hardcoded value (say, 0xFFFFFF for white) and it did work, so the problem is not there....
Hope you guys can help me out I've spent more than 4 hours on this already trying many different approaches!!
P.S.> I debugged this code in FB 4.5 and placed a breakpoint in that very if statement. For some reason, the _bmpData variable, which is where I want to get the original pixel color from , shows a small red square next to it.... Perhaps that is indicative of something.. perhaps it's somehow thread-'locked'?? I don't know, hope someone can figure out!
EDIT the problem I'm having is the following: the dimming of the image works fine, but if I then move the mouse cursor back to an area that got dimmed out, then the original image doesn't get repainted, as expected.
There must be something else going on there... I just tested your code and it worked fine for me.
package {
import flash.display.MovieClip;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.net.*;
import flash.display.Loader;
import flash.events.Event;
public class ImageCropper extends MovieClip {
protected var _bmpData:BitmapData;
protected var _mouseX:int;
protected var _mouseY:int;
var imageLoader:Loader;
public function ImageCropper() {
_mouseX = 80;
_mouseY = 50;
imageLoader = new Loader();
var image:URLRequest = new URLRequest("http://www.travelooce.com/pics/bear_picnic_table.jpg");
imageLoader.load(image);
imageLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, _imageLoaded);
imageLoader.x = 0;
imageLoader.y = 0;
}
public function _imageLoaded($evt:Event):void {
_bmpData = new BitmapData(imageLoader.width, imageLoader.height, false);
_bmpData.draw(imageLoader);
var bmp2:BitmapData = returnCropIndicatorBmpDataForTopLeft();
var bmp:Bitmap = new Bitmap(bmp2);
addChild(bmp);
}
private function returnCropIndicatorBmpDataForTopLeft():BitmapData{
var topLeftX:int = 0;
var topLeftY:int = 0;
var topRightX:int = _bmpData.width;
var topRightY:int = 0;
var bottomRightX:int = _bmpData.width;
var bottomRightY:int = _bmpData.height;
var bottomLeftX:int = 0;
var bottomLeftY:int = _bmpData.height;
var cropIconX:int = _mouseX;
var cropIconY:int = _mouseY;
// This is the important line to change.
var temporaryBitmapData:BitmapData = _bmpData.clone();
var originalColor:uint;
var dimmedColor:uint = 0x202020;
for (var i:int = 0; i < _bmpData.width; i++)
{
for (var j:int = 0; j < _bmpData.height; j++)
{
originalColor = _bmpData.getPixel(i,j);
if(i>cropIconX && j>cropIconY){
temporaryBitmapData.setPixel(i,j,originalColor);
}else{
temporaryBitmapData.setPixel(i,j,dimmedColor);
}
}
}
/*
*by the end of this loop, we have, in the temporaryBitmapData variable, a version of the _bmpData,
*the area to be cropped out dimmed a little bit.
*/
return temporaryBitmapData;
}
}
}
Output:
http://cl.ly/3d0h023C1p392O270I2L

Creating a parallax on a tiling background

I am using the blitting technique that Jeff from 8bitrocket.com uses for creating tiles. I am trying to paint 2 layers of bitmapdata onto a bitmap. One the first layer is the background ( 1 image). and the second layer is the tiles. In that class below. the updateMap is the method that gets called in the loop to repaint the image.
package com.eapi
{
/**
* ...
* #author Anthony Gordon
*/
import com.objects.XmlManager;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.*;
import flash.display.BitmapData;
import flash.display.Bitmap
import flash.geom.Rectangle;
import flash.geom.Point;
import flash.display.DisplayObject;
public class EngineApi extends MovieClip
{
public var images:Array;
public var world:Array;
//w stands for world, how big it is in columns and rows
private var wCols:Number = 50;
private var wRows:Number = 16;
public var wWidth:Number;
public var wHeight:Number;
//v stands for view, which means your field of view
public var vRows:Number;
public var vCols:Number;
public var vWidth:Number = 540;
public var vHeight:Number = 360;
//how big your indivual tile is
public var tileW:Number = 80;
public var tileH:Number = 80;
public var offsX:Number = 0;
public var offsY:Number = 0;
public var xEnd:Number = 0;
public var yEnd:Number = 0;
public var tilex:int;
public var tiley:int;
public var scrollx:Number = 0;
public var scrolly:Number = 0;
private var screen:Bitmap;
private var canvas:BitmapData;
private var buffer:BitmapData;
public var mapHolder:Array;
private var scrollLoop:Boolean;
private var minLoop:Number;
private var maxLoop:Number;
public var currentMap:Number = 0;
private var queue:Array;
public var currentCol:Number = 0;
public var currentRow:Number = 0;
public var enviroment:Array;
public var currentTileSheet:Number = 0;
private var layer1:Sprite;
private var layer2:Sprite;
private var layer3:Sprite;
private var layer4:Sprite;
private var layer5:Sprite;
public var background:BitmapData
protected var stageObject:Array;
protected var gameObjects:Array;
public function EngineApi(w:Number = 540,h:Number = 360, tw:Number = 50, th:Number = 50)
{
stageObject = new Array();
gameObjects = new Array();
//Add Layers
layer1 = new Sprite();
layer2 = new Sprite();
layer3 = new Sprite();
layer4 = new Sprite();
layer5 = new Sprite();
//end
images = new Array();
vWidth = w;
vHeight = h;
tileW = tw;
tileH = th;
queue = new Array();
mapHolder = new Array();
vCols = Math.floor(vWidth/tileW);
vRows = Math.floor(vHeight/tileH);
wWidth = wCols * tileW;
wHeight = wRows * tileH;
canvas = new BitmapData(vWidth,vHeight,true,0x000000);
buffer = new BitmapData(vWidth + 2 * tileW, vHeight + 2 * tileH ,false,0x000000);
screen = new Bitmap(canvas);
addChild(screen);
addChild(layer1);
addChild(layer2);
addChild(layer3);
addChild(layer4);
addChild(layer5);
}
public function addGameChild(object:IGameObject, layer:Number):void
{
switch(layer)
{
case 1:
layer1.addChild(DisplayObject(object));
break;
case 2:
layer2.addChild(DisplayObject(object));
break;
case 3:
layer3.addChild(DisplayObject(object));
break;
case 4:
layer4.addChild(DisplayObject(object));
break;
case 5:
layer5.addChild(DisplayObject(object));
break;
default:
}
if (object.IsDisplay == true)
gameObjects.push(object);
stageObject.push(object);
}
public function UpDateMap():void
{
offsX += scrollx;
offsY += scrolly;
tilex = int(offsX/tileW);
tiley = int(offsY/tileH);
xEnd = tilex + vWidth;
yEnd = tiley + vHeight;
var tileNum:int;
var tilePoint:Point = new Point(0,0);
var tileRect:Rectangle = new Rectangle(0, 0, tileW, tileH);
var rowCtr:int=0;
var colCtr:int=0;
for (rowCtr=0; rowCtr <= vRows; rowCtr++) {
for (colCtr = 0; colCtr <= vCols; colCtr++) {
currentCol = colCtr+tilex;
currentRow = rowCtr+tiley;
tileNum = mapHolder[currentMap][rowCtr+tiley][colCtr+tilex];
tilePoint.x = colCtr * tileW;
tilePoint.y = rowCtr * tileH;
tileRect.x = int((tileNum % 100))* tileW;
tileRect.y = int((tileNum / 100))* tileH;
buffer.copyPixels(images[currentTileSheet],tileRect,tilePoint);
}
}//End Loop
var bgRect:Rectangle = new Rectangle(0, 0, 544, 510);
var bgPoint:Point = new Point(0, 0);
var bufferRect:Rectangle = new Rectangle(0,0,vWidth,vHeight);
var bufferPoint:Point = new Point();
bufferRect.x = offsX % tileW;
bufferRect.y = offsY % tileH;
canvas.copyPixels(background,bgRect,bgPoint);
canvas.copyPixels(buffer,bufferRect,bufferPoint);
}//End UpdateMap
public function StartRender():void
{
addEventListener(Event.ENTER_FRAME, loop);
}
protected function loop(e:Event):void
{
UpDateMap();
UpdateObjects();
}
protected function UpdateObjects():void
{
for (var i:Number = 0; i < stageObject.length; i++)
{
stageObject[i].UpdateObject();
}
for (var g:Number = 0; g < stageObject.length; g++)
{
if (stageObject[g].Garbage && stageObject[g].IsDisplay)
{
removeChild(DisplayObject(stageObject[g]));
stageObject[g] = null;
}
else if (stageObject[g].Garbage == true && stageObject[g].IsDisplay == false)
{
stageObject[g] = null;
}
}
}
public function StopRender():void
{
removeEventListener(Event.ENTER_FRAME, loop);
}
}
}
It's not the complete code, but if I remove canvas.copyPixels(background,bgRect,bgPoint); or canvas.copyPixels(buffer,bufferRect,bufferPoint); I can see either or. If I paint them both then I can only see the one that painted last. My tile image is 128 x 32. 0 - 3. array 3 is transparent image. I used that hoping that I could see through the image and see the background. I was wrong.
At first it was an all black background, but then I changed the transparent constructor to true on the buffer variable. Now it shows a white background (like the stage), but still no background image.
I'm not sure I completely understand the example, but it looks like the issue is that you're using copyPixels--this should replace the old pixels in the canvas bmp with new values.
Try using draw for the foreground instead:
canvas.copyPixels(background, bgRect, bgPoint);
canvas.draw(buffer, transform, null, null, clipRect);
Also, I'm not sure why you're drawing the background image to a different rect than the foreground? There may be something there.
I took a seperate movieclip and used it as a parallax behind the blitting tiles.

Resources