TweenLite/TweenMax support for ConvolutionFilter - actionscript-3

I am applying filters to a bitmap using something like:
TweenLite.to(origBitmap,0,{colorMatrixFilter:{saturation:2,brightness:3});
and that works fine.
I need to somehow apply a sharpen filter to origBitmap which I have successfully achieved using a ConvolutionFilter. The problem is after I've ran the above tweenlite call, then create a convolution filter and apply it to origBitmap, it removes the initial saturation and brightness filters and just keeps the sharpen filter
private function applyEffects(effects:Array):void
{
currentEffects = effects;
var props:Object = {};
for (var i:String in effects)
{
props[effects[i].effect] = effects[i].amount;
}
TweenLite.to(bitmap,0,{colorMatrixFilter:props});
//-- props could look like {saturation:2,brightness:3}
//-- This will sharpen the container sprite
var matrix:Array = [0, -1, 0,
-1, 5, -1,
0, -1, 0];
var conv:ConvolutionFilter = new ConvolutionFilter();
conv.matrixX = 3;
conv.matrixY = 3;
conv.matrix = matrix;
conv.divisor = 1;
bitmap.filters = [conv]; //-- this removes the above filters and just sharpens the image
}
Is there a way to also incorporate the ConvolutionFilter in that TweenLite call above? I've searched quite a bit and found some guy made a class called TweenMan which was based around your class where ConvolutionFilter is incorporated: https://github.com/danro/tweenman-as3

Nothing to do with TweenMax here since your code is the one making the mistake. This correctly removes all current filter and apply only one:
bitmap.filters = [conv];
Since filters property is either null or is an Array. To add a filter to the list you use array operation and reapply the array:
var filters:Array = bitmap.filters;
if(!filters)
{
filters = [];
}
filters.push(conv);
bitmap.filters = filters;
EDIT: starting over since I think I understand what you are trying to do. You are avoiding creating the filter yourself and let TwennLite do it for you even tough you don't need to tween anything. Don't do that, you are making everything harder for yourself. Instead create your filter that way:
var props:Object = {};
var colorMatrix:ColorMatrixFilter = new ColorMatrixFilter();
for (var i:String in effects)
{
colorMatrix[effects[i].effect] = effects[i].amount;
}
bitmap.filters = [colorMatrix];
//etc .... then
var filters:Array = bitmap.filters;
filters.push(conv);
bitmap.filters = filters;
If you need to animate multiple filters remember that most tween engine can tween easily array values so you can just do that and then apply those array values to your filters.

Related

How can I translate keyword prototype in AS3 to Haxe?

I have the below AS3 code, and I want to translate it to Haxe. But I don't know how to deal with the keyword prototype. Who can help me? Thanks.
var style = new CSSStyleDeclaration();
style.defaultFactory = function():void
{
this.disabledOverlayAlpha = 0;
this.borderStyle = "controlBar";
this.paddingTop = 10;
this.verticalAlign = "middle";
this.paddingLeft = 10;
this.paddingBottom = 10;
this.paddingRight = 10;
};
if(chain == null) chain = {};
style.defaultFactory.prototype = chain;
chain = new style.defaultFactory();
style.defaultFactory = function():void
{
this.fontWeight = "bold";
};
style.defaultFactory.prototype = chain;
chain = new style.defaultFactory();
style.defaultFactory = function():void
{
this.backgroundSize = "100%";
this.paddingTop = 24;
this.backgroundColor = 8821927;
this.backgroundImage = ApplicationBackground;
this.horizontalAlign = "center";
this.backgroundGradientAlphas = [1,1];
this.paddingLeft = 24;
this.paddingBottom = 24;
this.paddingRight = 24;
};
style.defaultFactory.prototype = chain;
chain = new style.defaultFactory();
Ok, I poked this a bit, and now I kind of figured out, what that piece of code does. This knowledge won't help you to port your code to HAXE, but it will help you understand what it is about and to compose a decent HAXE-style alternative.
First, the part about instantiating, functions and working with prototypes. As it turned out, if you invoke the new operator on an unbound function (does not work on class methods):
The new empty class-less generic Object is created.
Its reference is passed to the said function as this.
The function can add and modify the object's fields and methods.
Ultimately, the reference to that Object is returned.
Then, it works (as I mentioned in my comments above) very much the way classes worked back then in AS1 and Flash 6.
If that function has a prototype and it is too a generic Object, then it is added to the newly created one as a... how to put it... a bottom layer Object which adds its fields to the top layer Object.
I understand that it sounds difficult, so there's an explanatory example that somehow sheds some light on it all:
public class Proton extends Sprite
{
public function Proton()
{
super();
var P:Function;
// Empty.
P = new Function;
create("First:", P);
// Empty with prototype.
P.prototype = {c:3, d:4};
create("Second:", P);
// Non-empty.
P = function():void
{
this.a = 1;
this.b = 2;
};
create("Third:", P);
// Non-empty with prototype.
P.prototype = {a:5, f:6};
create("Fourth:", P);
}
// Instantiates the F and outputs the result.
private function create(prefix:String, F:Function):void
{
var A:Object = new F;
trace(prefix + "\nJSON:" + JSON.stringify(A) + "\nREAL:" + explore(A) + "\n");
}
// Same as JSON.stringify, but also looks into the prototype.
private function explore(O:Object):String
{
var result:Array = new Array;
for (var akey:String in O)
{
result.push('"' + akey + '":' + O[akey]);
}
return "{" + result.join(",") + "}";
}
}
So, the output is:
First:
JSON:{}
REAL:{}
Second:
JSON:{}
REAL:{"d":4,"c":3}
Third:
JSON:{"b":2,"a":1}
REAL:{"b":2,"a":1}
Fourth:
JSON:{"b":2,"a":1}
REAL:{"b":2,"a":1,"f":6,"a":1}
As you can see, JSON.stringify exports only the top layer object, while direct for iteration goes through all the layers, top to bottom, and even processes the duplicate keys (but the top layer value shadows what's below).
Second, how it all is related to your code. These factory and defaultFactory functions are used in some CSS-related class to form an Object representation of the style: https://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/styles/CSSStyleDeclaration.html
So, you can use that prototype hack to form a generic Object with a chain of layers upon layers of CSS declarations... probably. You saw that JSON doesn't perceive anything but the top layer, I have no idea if CSS classes act differently or not.
I think, working with CSS should be less hack-y and more straightforward.
Good luck figuring it out.

AS3 - Using a For Loop to Update Multiple Points and Their Values in an Array

I'm a bit new with AS3 (but not really with coding) so please forgive my ignorance. I'm creating a small function that will be called by a Main Function to update the position of 52 Pointers that have the x and y position of multiple point objects (empty movie clips). It will also then update two global arrays with those values (one array for the x and one for the y).
The problem is, as there are 52 of them, and they will probably grow in quantity, I'd like to be able to use a FOR function to do it, but I can't seem to be able to figure it out.
I get this error: Access of undefined property _point.
Here is a piece of the code that dream about:
function happyFunc():void
{
var avpointers:int = 52;
var vpointx:Array = new Array();
var vpointy:Array = new Array();
for (aa=0; aa<vpointers; aa++)
{
vpointx[aa] = _point[aa].x;
vpointy[aa] = _point[aa].y;
}
}
And this is the code that I'm stuck with...
function reallySadFunc():void
{
_point1 = localToGlobal(new Point(point1.x,point1.y));
//...
_point52 = localToGlobal(new Point(point52.x,point1.y));
vpointx[0] = _point1.x;
vpointx[1] = _point2.x;
//...
//oh god there are 104 lines of this why do I have to suffer
}
Thank you!
If I read your question correctly, I think this is what you need:
public static const CLIP_COUNT:int = 52;
// ...
private function happyFunc(parentClip:DisplayObjectContainer):void
{
var vpointx:Vector.<Number> = new Vector.<Number>(CLIP_COUNT, true);
var vpointy:Vector.<Number> = new Vector.<Number>(CLIP_COUNT, true);
var clipPoint:Point = new Point ();
var globalPoint:Point;
for (var i:int = 0; i < CLIP_COUNT; i++)
{
var childClip:DisplayObject = parentClip.getChildByName("point" +
(i + 1).toString());
clipPoint.x = childClip.x;
clipPoint.y = childClip.y;
globalPoint = parentClip.localToGlobal(clipPoint);
vpointx[i] = globalPoint.x;
vpointy[i] = globalPoint.y;
}
// do something with vpointx and vpointy - they're local variables
// and will go out of scope unless you declare them as class members
// or somehow return them from this function.
}
This function works by taking the parent display object (the one that contains the 52 movie clips - this could be the Stage) and iterates through them by getting each movie clip by name. The code assumes that your movie clips are called point1, point2, ..., point52.
To speed up the local-to-global coordinate conversion, two Point objects are created and then reused during the for loop to avoid creating many temporary Point instances.
Instead of using Array, use Vector.<Number> - this class has better performance than Array does.

AS3 .addEventListener in a loop?

I am creating a line of Sprite elements. Every sprite element has different job, when it is clicked. How can I make the function inside the addEventListener to know which button was clicked?
In this case, the traced value of i when it is cliicked is always 6. Which is wrong, because 6 is only the last element of the array. What about the rest of them, the beginning?
for (var i:int = 0; i < 6; i++) {
var barPart:Sprite = new Sprite();
barPart.x = i * (30);
barPart.y = 0;
barPart.graphics.beginFill(0x000000, 0.2);
barPart.graphics.drawRect(0, 0, 10, 10);
barPart.graphics.endFill();
barPart.addEventListener(MouseEvent.CLICK, function(_event:MouseEvent):void {
trace(i);
});
}
When the application is build and the listeners are added, the loop has already executed, so the index "i" will always be six by the time the user ends up clicking the button.
To distinguish between the different items, use their "name" property (prop of DisplayObject) like shown ...
Try not to have listener function as a method closure in a loop, instead do this:
for (...)
{
... code
barPart.name = "barPart-" +i;
barPart.addEventListener(MouseEvent.CLICK, barPart_clickHandler);
}
and implement the function (event handler separately) like:
private function barPart_clickHandler(e:MouseEvent):void
{
// the event's target will let you know who dispatched the function
var name:String = Sprite(e.currentTarget).name;
name = name.replace("barpart-", "");
switch(name)
{
case '0':
// your code
break;
.
.
}
}
#Shally Virk - My mistake. I was thinking of MovieClip which is a dynamic object so it allows adding arbitrary fields. You are right, there are lots of ways to get around this problem, but your suggestion works fine.
While the cause is not clear to me, the answer is a little more simple,
The events are registered correctly, but flash takes the last computed value.
Knowing that we can work around.
The work around can either do like Shally Virk wrote, but that tends to get confusing on bigger scale. So we want something more general and simple.
Now here are the steps taking this in mind:
1. We know sprite are not dynamic, so we make class to extend spirte and make it dynamic. Since the class has basically 0 code, the only difference being the dynamic , the amount of memory added is small
2. Having the class here's the code:
for (var i:int = 0; i < 6; i++) {
var barPart:CustomSprite = new CustomSprite();
barPart.x = i * (30);
barPart.y = 0;
barPart.graphics.beginFill(0x000000, 0.2);
barPart.graphics.drawRect(0, 0, 10, 10);
barPart.graphics.endFill();
barPart.i = i;
barPart.addEventListener(MouseEvent.CLICK, function(_event:MouseEvent):void {
trace(_event.currentTarget.i);
});
}
:)

Unloading a Loader with actionscript 3

Hello and thank you very much for looking at this. I've spent too many hours struggling.
The code below loads a slideshow of four images, along with thumbnails for those images. It works fine.
I've added a button called "invis_button", that when pressed is supposed to remove the 3 loaders that make up the slideshow, using the removeChild command for each loader.
But this is the problem, there are 3 loaders involved in the slide-show. The removeChild command successfully removes one of the loaders (named "loader3"), but not the other two ("container3", and "thumbLoader3"). It returns an error stating "access of undefined property thumbLoader3" or "Container3".
Can someone tell me why this is ? Or better still, how to make that button (invis_button) unload the entire slide-show.
var images3:Array = ["ad_bona1.jpg", "ad_bona2.jpg", "ad_darkhawk1.jpg", "ad_darkhawk2.jpg"];
var thumbX3:Number = -375;
var thumbY3:Number = 220;
var loader3:Loader = new Loader();
loader3.load(new URLRequest("assets/ad_bona1.jpg"));
addChild(loader3);
loader3.alpha = 0;
loadThumbs3();
function loadThumbs3():void
{
var thumbLoader3:Loader;
var container3:Sprite = new Sprite();
addChild(container3);
container3.buttonMode = true;
for(var i3:uint = 0; i3 < images3.length; i3++)
{
thumbLoader3 = new Loader();
thumbLoader3.load(new URLRequest("assets/thumbs/" + images3[i3]));
thumbLoader3.x = thumbX3;
thumbLoader3.y = thumbY3;
thumbX3 += 85;
container3.addChild(thumbLoader3);
thumbLoader3.addEventListener(MouseEvent.CLICK, thumbClicked3);
}
}
function thumbClicked3(event:MouseEvent):void
{
var path3:String = event.currentTarget.contentLoaderInfo.url;
path3 = path3.substr(path3.lastIndexOf("/") + 1);
loader3.load(new URLRequest("assets/" + path3));
}
///PROBLEM BELOW, button removes only "loader3" and not the other two for some reason
invis_button.addEventListener(MouseEvent.CLICK, unload_loaders);
function unload_loaders(event:MouseEvent):void{
removeChild(loader3);
removeChild(thumbLoader3);
removeChild(container3);
}
Not sure if this is the entire reason behind what you're observing... but for starters, "thumbloader3" and "container3" are scoped locally to the loadThumbs3() method, which means once you finish executing the function, Flash's handles to those objects are lost (not to mention being in an entirely different scope)... try creating class-level properties for those two. Once that's done you should be able to successfully remove them from the stage later on.
I hope that you're also properly destroying your objects, and for the sake of brevity you just chose to omit that code above.
I've edited the code you had above & put the properties into the proper scope. (the multiple copies of thumbLoader3 are now collected inside of a vector (specialized array) so that they can be properly addressed when it comes time to destroy them)
I also wrote you a proper destroy method. ;)
I haven't tried it on my own machine, but give it a spin & see how it goes.
var images3:Array = ["ad_bona1.jpg", "ad_bona2.jpg", "ad_darkhawk1.jpg", "ad_darkhawk2.jpg"];
var thumbX3:Number = -375;
var thumbY3:Number = 220;
// begin new instance properties..
// created a new property, allowing you to group (and hold on to) the multiple thumbLoaders
var thumbLoader3Vector:Vector.<Loader> = new Vector.<Loader>();
var container3:Sprite;
// end new instance properties
var loader3:Loader = new Loader();
loader3.load(new URLRequest("assets/ad_bona1.jpg"));
addChild(loader3);
loader3.alpha = 0;
loadThumbs3();
function loadThumbs3():void
{
// this is where container3 used to be declared
container3 = new Sprite();
addChild(container3);
container3.buttonMode = true;
for(var i3:uint = 0; i3 < images3.length; i3++)
{
var tPtr:int = thumbLoader3Vector.length;
thumbLoader3Vector.push(new Loader());
// this is where thumbLoader3 used to be declared & instantiated
thumbLoader3Vector[tPtr].load(new URLRequest("assets/thumbs/" + images3[i3]));
thumbLoader3Vector[tPtr].x = thumbX3;
thumbLoader3Vector[tPtr].y = thumbY3;
thumbX3 += 85;
container3.addChild(thumbLoader3Vector[tPtr]);
thumbLoader3Vector[tPtr].addEventListener(MouseEvent.CLICK, thumbClicked3);
}
}
function thumbClicked3(event:MouseEvent):void
{
var path3:String = event.currentTarget.contentLoaderInfo.url;
path3 = path3.substr(path3.lastIndexOf("/") + 1);
loader3.load(new URLRequest("assets/" + path3));
}
///PROBLEM BELOW, button removes only "loader3" and not the other two for some reason
invis_button.addEventListener(MouseEvent.CLICK, unload_loaders);
function unload_loaders(event:MouseEvent):void{
// since the thumbLoader3 Loaders are children of container3 in the display list, we need to remove them first
for(var $i:uint = 0;$i<thumbLoader3Vector.length;$i++)
{
removeChild(thumbLoader3Vector[$i]);
// also make sure you remove the listener, so that the object will be picked up by garbage collection
thumbLoader3Vector[$i].removeEventListener(MouseEvent.CLICK, thumbClicked3);
}
// and then just set the entire vector to null
thumbLoader3Vector = null;
// remove the loader3 object & set it to null
removeChild(loader3);
loader3 = null;
// remove the container3 object & set it to null
removeChild(container3);
container3 = null;
}

Add multiple movieclips, not replacing the old ones

So, in short, my problem is this. I am using a variable which is a movieclip loaded from an external swf. I want to "spawn" multiple instances of the movieclip that all react to the same code, so for example if I say var1.x = 100, they all are at 100x. But my problem is when I run addChild(var1) multiple times(I'm not actually typing in addChild(var1) over and over, I just have it set to add them at random times), the new child just replaces the old one, instead of making multiple movieclips. Should I do something like
var var1:MovieClip
var var2:MovieClip = new var1 ?(which doesnt work for me btw, gives me errors)
Oh, heres the code, and also, I am pretty new to as3 fyi, still don't even know how arrays work, which was my second guess to the problem.
var zombieExt:MovieClip;
var ldr2:Loader = new Loader();
ldr2.contentLoaderInfo.addEventListener(Event.COMPLETE, swfLoaded2);
ldr2.load(new URLRequest("ZombieSource.swf"));
function swfLoaded2(event:Event):void
{
zombieExt = MovieClip(ldr2.contentLoaderInfo.content);
ldr2.contentLoaderInfo.removeEventListener(Event.COMPLETE, swfLoaded2);
//zombieExt.addEventListener(Event.ENTER_FRAME, moveZombie)
zombieExt.addEventListener(Event.ENTER_FRAME,rotate2);
function rotate2 (event:Event)
{
var the2X:int = playerExt.x - zombieExt.x;
var the2Y:int = (playerExt.y - zombieExt.y) * 1;
var angle = Math.atan(the2Y/the2X)/(Math.PI/180);
if (the2X<0) {
angle += 180;
}
if (the2X>=0 && the2Y<0) {
angle += 360;
}
//angletext.text = angle;
zombieExt.rotation = (angle*1) + 90;
}
playerExt.addEventListener(Event.ENTER_FRAME,spawn1);
function spawn1 (event:Event)
{
if(playerExt.y < 417)
{
var someNum:Number = Math.round(Math.random()*20);
if(someNum == 20)
{
addChild(zombieExt)
zombieExt.x = Math.round(Math.random()*100)
zombieExt.y = Math.round(Math.random()*100)
}
}
}
}
addChild() does not create new instances. It is used to add an already created instance to the display list. If you call addChild() multiple times on the same instance then you are just readding itself.
Also each instance is unique, you can not globally change the x position of an instance by changing another one of them. What you would do is as Henry suggests and add each new instance of a MovieClip into an array, then whenever you change something you can loop through the array and apply the changes to each instance.
You can not go var2:MovieClip = new var1 either since var1 is an instance and not a class.
Here's a different method of receiving loaded MovieClips, which i use when i need many copies of the item.
in the swf you are loading, give the target movieclip a linkage name in the library, for this example i will use "foo"
private var loadedSwfClass:Class
private var newZombie:MovieClip;
private var zombieArray:Array = new Array();
function swfLoaded2(event:Event):void
{
loadedSwfClass = event.target.applicationDomain.getDefinition("foo");
for(var n:int = 0; n<100; n++){
newZombie = new loadedSwfClass()
zombieArray.push(newZombie);
addChild(newZombie);
}
}
as per this tutorial
http://darylteo.com/blog/2007/11/16/abstracting-assets-from-actionscript-in-as30-asset-libraries/
although the comments say that
var dClip:MovieClip = this;
var new_mc = new dClip.constructor();
this.addChild(new_mc);
will also work.
It sounds like you might be accessing the same instance some how in your code. It would be helpful to see your code to figure this one out.
If I wanted to load in one swf files and add a MovieClip multiple times I would place it in the library of that SWF file. And then instantiate it and store it into an object pool or a hash or some list.
// after the library were finished loading
var list:Array = [];
for(var i:int=0; i<10; i++) {
var myCreation:MySpecialThing = new MySpecialThing();
addChild(myCreation);
list.push(myCreation);
}
where my library would contain a linkage to the class MySpecialThing.
Calling addChild(var1) multiple times on the same parent doesn't have any effect (unless you have added another child to the same parent in between, in which case it will change the child index and bring var1 to the top). If you call it on different parents, it will just change the parent of var1, doesn't duplicate. Call addChild(new MovieClassName()) at random times instead to add new copies of it. Use an array as suggested here to access them later.
Wow, thanks there henry, just using an array did exactly what I needed, and made things alot simpler.
when you load in using a loader you only get 1 instance, however you can do some funky reflection to determine what class type the given loader.content is, and then instantiate them using that. For Example:
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loader_completeHandler);
loader.load(new URLRequest("ZombieSource.swf"));
var classType:Class;
function loader_completeHandler(evt:Event):void
{
var loadInfo:LoaderInfo = (evt.target as LoaderInfo);
var loadedInstance:DisplayObject = loadInfo.content;
// getQualifiedClassName() is a top-level function, like trace()
var nameStr:String = getQualifiedClassName(loadedInstance);
if( loadInfo.applicationDomain.hasDefinition(nameStr) )
{
classType = loadInfo.applicationDomain.getDefinition(nameStr) as Class;
init();
}
else
{
//could not extract the class
}
}
function init():void
{
// to make a new instance of the ZombieMovie object, you create it
// directly from the classType variable
var i:int = 0;
while(i < 10)
{
var newZombie:DisplayObject = new classType();
// your code here
newZombie.x = stage.stageWidth * Math.random();
newZombie.x = stage.stageHeight * Math.random();
i++;
}
}
Any problems let me know, hope this helps.