Este prototipo devuelve la primera posición que encuentra del parametro pasado dentro del array.
Actionscript:
Array.prototype.firstIndexOf = function(n) {
var l = this.length;
for (var i = 0; i <l; i++) {
if (this[i] == n) {
return i;
}
}
return -1;
};
//Uso:
mi_array=["a","b","c","d","e","f"];
trace(mi_array.firstIndexOf("d"));
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
array
Un simple prototipo para desordenar una array aleatoriamente.
Actionscript:
Array.prototype.randomize = function() {
var l = this.length;
for (var i = 0; i <l; i++) {
var alea = Math.ceil(Math.random() * l);
var tmp = this[i];
this[i] = this[alea];
this[alea] = tmp;
}
};
//Uso:
mi_array=[1,2,3,4,5,6,7];
mi_array.randomize();
trace(mi_array);
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
array
Este prototipo pasa a blanco y negro el movieClip sobre el que se aplica. La primera versión sencillamente desatura, y la segunda crea un duplicado sobre el mc original para tener disponible el item original en color, para por ejemplo un rollOver ;)
Actionscript:
import flash.filters.ColorMatrixFilter;
MovieClip.prototype.desaturate = function():Void {
var bn_filter:ColorMatrixFilter = new ColorMatrixFilter([0.3, 0.59, 0.11, 0, 0, 0.3, 0.59, 0.11, 0, 0, 0.3, 0.59, 0.11, 0, 0, 0, 0, 0, 1, 0]);
this.filters = [bn_filter];
};
//Uso:
mc.desaturate();
Actionscript:
import flash.filters.ColorMatrixFilter;
MovieClip.prototype.desaturateAndDuplicate = function():Void {
var bn_filter:ColorMatrixFilter = new ColorMatrixFilter([0.3, 0.59, 0.11, 0, 0, 0.3, 0.59, 0.11, 0, 0, 0.3, 0.59, 0.11, 0, 0, 0, 0, 0, 1, 0]);
var bmp = new flash.display.BitmapData(this._width, this._height, true, 0x00000000);
var bn:MovieClip = this._parent.createEmptyMovieClip("bn_mc", 2);
bn.attachBitmap(bmp,0);
bmp.draw(this);
bn.filters = [bn_filter];
this._visible = false;
};
//Uso:
mc.desaturateAndDuplicate();
Imprescindible haber importado el filtro ColorMatrixFilter.
Este sencillo prototipo se encarga de convertir un movieclip en imagen con la propiedad smooth activada para poder escalarlo sin ese horrible efecto pixelado. Combinado con MovieClipLoader es especialmente útil para escalar imágenes externas cargadas dinámicamente con un poco de dignidad.
Actionscript:
MovieClip.prototype.smoothBitmap = function():Void {
var bmp = new flash.display.BitmapData(this._width, this._height, true, 0x000000);
bmp.draw(this);
this.attachBitmap(bmp,0,"auto",true);
};
//Uso:
var dummyholder:MovieClip = this.createEmptyMovieClip("holder", this.getNextHighestDepth());
var mcl:MovieClipLoader = new MovieClipLoader();
var mcl_ls:Object = new Object();
mcl.addListener(mcl_ls);
mcl_ls.onLoadInit = function(target:MovieClip):Void {
target.smoothmeslowlyplease();
};
mcl.loadClip("http://drusunlimited.com/portfolio/img/tarjeta.png",dummyholder);
Ojo con el consumo de memoria.
Este prototipo simplifica el manejo de coordenadas de movieClips anidados, al devolver la posicion absoluta del clip.
Actionscript:
MovieClip.prototype.globalize = function() {
var sum:Array = new Array(this._x, this._y);
var parent:MovieClip = this._parent;
while (parent) {
sum[0] += parent._x;
sum[1] += parent._y;
parent= parent._parent;
}
return sum;
};
//Uso:
trace(my_mc.globalize()[0]); //devuelve la coordenada _x absoluta
trace(my_mc.globalize()[1]); //devuelve la coordenada _y absoluta
Este prototipo es uno de tantos que valida emails:
Actionscript:
String.prototype.isEmail = function() {
if (!this) {
return false;
}
var iChars = "*|,\":<>[]{}`';()&$#% ";
for (var i = 0; i<this.length; i++) {
if (iChars.indexOf(this.charAt(i)) != -1) {
return false;
}
}
if (this.indexOf("@") == -1) {
return false;
}
if (this.indexOf(".") == -1) {
return false;
}
return true;
};
//Uso:
mail="jaja@pua.es";
trace(mail.isEmail());
Este protipo dibuja un marco, del grosor definido por borderThickness, alrededor del mc sobre el que se aplica (obj_mc). Si el valor de borderThickness es negativo, el marco se aplica hacia fuera.
Actionscript:
MovieClip.prototype.drawFrame = function(borderThickness:Number, borderColor:Number) {
this.p = this.getBounds();
var frame_mc:MovieClip = this.createEmptyMovieClip("frame_mc", 0);
frame_mc.beginFill(borderColor, 100);
frame_mc.moveTo(this.p.xMin+borderThickness, this.p.yMin+borderThickness);
frame_mc.lineTo(this.p.xMax-borderThickness, this.p.yMin+borderThickness);
frame_mc.lineTo(this.p.xMax-borderThickness, this.p.yMax-borderThickness);
frame_mc.lineTo(this.p.xMin+borderThickness, this.p.yMax-borderThickness);
frame_mc.lineTo(this.p.xMin+borderThickness, this.p.yMin+borderThickness);
frame_mc.moveTo(this.p.xMin, this.p.yMin);
frame_mc.lineTo(this.p.xMin, this.p.yMax);
frame_mc.lineTo(this.p.xMax, this.p.yMax);
frame_mc.lineTo(this.p.xMax, this.p.yMin);
frame_mc.endFill();
};
//Uso: borderThickness,borderColor
//un borderThickness positivo enmarca hacia dentro
//un borderThickness negativo enmarca hacia fuera
obj_mc.drawFrame(15, 0x666666);
obj2_mc.drawFrame(-15, 0x999999);
Mi versión de los tweens, usando las ecuaciones de Robert Penner.
Actionscript:
MovieClip.prototype.easeInOut = function(t:Number, b:Number, c:Number, d:Number):Number {
if ((t /= d/2)<1) {
return c/2*t*t*t*t*t+b;
}
return c/2*((t -= 2)*t*t*t*t+2)+b;
};
MovieClip.prototype.myTween = function(prop, destino, duracion) {
var dummy:MovieClip = this._parent.createEmptyMovieClip("dummy"+random(5000), this._parent.getNextHighestDepth());
este = this;
dummy.propini = this[prop];
dummy.dx = destino-this[prop];
dummy.t = 5;
dummy.duracion = duracion;
dummy.onEnterFrame = function() {
if (this.t++<duracion) {
este[prop] = este.easeInOut(this.t, this.propini, this.dx, this.duracion);
} else {
delete this.onEnterFrame;
removeMovieClip(this);
}
};
};
//Uso:
_root.onMouseDown = function() {
obj_mc.myTween("_x", _root._xmouse, 50);
obj_mc.myTween("_y", _root._ymouse, 50);
};
¿necesita alguna explicación?
Actionscript:
MovieClip.prototype.drawCircle = function(radius, x, y, col) {
var angleDelta = Math.PI/4;
var ctrlDist = radius/Math.cos(angleDelta/2);
var angle = 0;
var rx, ry, ax, ay;
this.beginFill(col, 100);
this.moveTo(x+radius, y);
for (var i = 0; i<8; i++) {
angle += angleDelta;
rx = x+Math.cos(angle-(angleDelta/2))*(ctrlDist);
ry = y+Math.sin(angle-(angleDelta/2))*(ctrlDist);
ax = x+Math.cos(angle)*radius;
ay = y+Math.sin(angle)*radius;
this.curveTo(rx, ry, ax, ay);
}
this.endFill();
};
Este prototipo crea un marco del grosor y color definidos en sus parámetros sobre el movieClip en que se aplica. También asigna métodos onRollOver y onRollOut a dicho movieClip para escalar el grosor del marco.
Requiere la librería de
Laco,
Zeh, o similar.
Descargable frameOver prototype
Actionscript:
#include "lmc_tween.as"
MovieClip.prototype.frameOver = function(grosor,color) {
var over:MovieClip = this.createEmptyMovieClip("over", 1);
var l:MovieClip = over.createEmptyMovieClip("l", 1);
var escalax = (this._width+grosor*2)/100*grosor;
var escalay = this._height/100*grosor*2;
var w:Number = this._width;
var h:Number = this._height;
l.lineStyle(0, 0x000000, 0);
l.beginFill(color, 100);
l.moveTo(0, -h/2);
l.lineTo(grosor, -h/2);
l.lineTo(grosor, h/2);
l.lineTo(0, h/2);
l.lineTo(0, -h/2);
l.endFill();
l._y = h/2;
l._xscale = .1;
var t:MovieClip = l.duplicateMovieClip("t", 2, {_x:w/2, _y:0, _rotation:90});
var r:MovieClip = l.duplicateMovieClip("r", 3, {_x:w, _y:h/2, _rotation:180});
var b:MovieClip = l.duplicateMovieClip("b", 4, {_x:w/2, _y:h, _rotation:270});
t._yscale = b._yscale=w/h*100;
this.onRollOver = function() {
l.tween("_xscale", 100, 1);
t.tween("_xscale", 100, 1);
r.tween("_xscale", 100, 1);
b.tween("_xscale", 100, 1);
};
this.onRollOut = function() {
l.tween("_xscale", .1, .5);
t.tween("_xscale", .1, .5);
r.tween("_xscale", .1, .5);
b.tween("_xscale", .1, .5);
};
};
//Uso:
obj_mc.frameOver(15,0x666666);
Prototipo que extrae una subcadena de palabras completas de la cadena sobre la que se aplica.
Útil para crear entradillas de artículos más extensos.
Actionscript:
String.prototype.entradilla = function(ini,fin) {
var texto= this.substr(ini,fin);
var palabras_ar = texto.split(" ");
var entradilla = "";
for(var i=0; i<(palabras_ar.length-1);i++) {
entradilla += palabras_ar[i] + " ";
}
entradilla = entradilla.substr(0,entradilla.length-1);
return entradilla;
};
Con este sencillo prototipo eliminamos los molestos y habituales dobles retornos de carro de un archivo de texto externo cargado dinámicamente.
Actionscript:
String.prototype.cleanReturns = function() {
return this.split("\n\r").join("\n");
};
//Uso:
textbox.text = this.txt.cleanReturns();
Enlaces relacionados: No related posts, | Tags:
actionscript,
texto,
prototipo,
String
Este prototipo crea un efecto de reflejo del movieClip sobre el que se aplica, duplicandolo, volteandolo y aplicándole un degradado lineal que lo funde sobre un fondo blanco.
Desgraciadamente, si la imagen es cargada dinámicamente, también hay que cargarla en el duplicado, ya que se duplica el movieClip en su estado inicial (shit!).
Actionscript:
//http:drusunlimited.com
MovieClip.prototype.reflex = function() {
var reflejo:MovieClip = this.duplicateMovieClip(this._name+"reflejo", this.getDepth()+100);
reflejo._yscale = -100;
reflejo._y = this._y+this._height*2;
var degrade:MovieClip = reflejo.createEmptyMovieClip("degrade_mc", 1);
degrade.fillType = "linear";
degrade.colors = [0xFFFFFF, 0xFFFFFF];
degrade.alphas = [100, 80];
degrade.ratios = [150, 255];
degrade.matrix = {matrixType:"box", x:0, y:0, w:this._width, h:this._height, r:90/180*Math.PI};
with (degrade) {
beginGradientFill(fillType, colors, alphas, ratios, matrix);
lineStyle(5, 0xFF00FF, 0);
moveTo(0, 0);
lineTo(this._width, 0);
lineTo(this._width, this._height);
lineTo(0, this._height);
moveTo(0, 0);
endFill();
}
};
//Uso:
obj_mc.reflex();
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
efecto,
MovieClip
Permite subir o bajar el volumen de un sonido gradualmente hasta el volumen deseado, en el tiempo establecido por el parámetro "duration".
Actionscript:
Sound.prototype.fadeVolume = function(level, duration) {
var me = this;
if (duration == undefined) {
duration = 1000;
}
clearInterval(me.intervalID);
me.intervalID = setInterval(function () {
me.vol = me.getVolume();
if (level-me.vol>0) {
me.inc = 1;
} else {
me.inc = -1;
}
if (Math.abs(me.vol-level)>0) {
me.setVolume(me.vol+me.inc);
} else {
clearInterval(me.intervalID);
}
}, duration/100);
};
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
Sound,
fade,
volume
Estos dos prototipos nos permiten detener todos los movieclips contenidos en la timeline sobre la que se aplica. "stopAllMovieClips" ejecuta un bucle en busca de movieclips aplicando un stop() en cada y guardandolos en una matriz, para que luego el prototipo "playStoppedMovieClips" pueda ponerlos en funcionamiento de nuevo.
Pendiente averiguar qué movieclips están en ejecución y cuales no, ya que por ahora detiene y pone en marcha todos, independientemente de que estuvieran en marcha o no en el momento de detenerse.
Actionscript:
MovieClip.prototype.stopAllMovieClips = function() {
stopped_ar = new Array();
for (var mc in this) {
if (typeof (this[mc]) == "movieclip") {
//this[mc].stop();
this[mc].stopMovieClips();
stopped_ar.push(this[mc]);
}
this.stop();
stopped_ar.push(this);
}
};
MovieClip.prototype.playStoppedMovieClips = function() {
for (var i = 0; i<stopped_ar.length; i++) {
stopped_ar[i].play();
}
};
//Uso
_root.onMouseDown = function() {
stopMovieClips();
};
_root.onMouseUp = function() {
playStoppedMovieClips();
};
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
timeline,
MovieClip
Este prototipo dibuja rectángulos por medio de la API de dibujo de flash. Muy completo, permite especificar incluso la redondez de las esquinas.
Lo lamento pero no sé de dónde demonios lo saqué :(
Quizás de after-hours o de prototype aunque lo busco y no lo encuentro
Actionscript:
MovieClip.prototype.drawRectangle = function(Nombre, Radio, AnchoT, AltoT, colorFondo, colorLinea, Trazo, Alfa, Prof) {
this.createEmptyMovieClip(Nombre, prof);
Ancho = AnchoT-Radio;
Alto = AltoT-Radio;
clip = this[Nombre];
vel = .1;
with (clip) {
lineStyle(Trazo, colorLinea);
beginFill(colorFondo, Alfa);
moveTo(Radio, 0);
lineTo(Ancho, 0);
for (ang=270*(Math.PI/180); ang<=360*(Math.PI/180); ang += vel) {
x = Ancho+Radio*Math.cos(ang);
y = Radio+Radio*Math.sin(ang);
lineTo(x, y);
}
lineTo(AnchoT, Alto);
for (ang=0; ang<=90*(Math.PI/180); ang += 0.05) {
x = Ancho+Radio*Math.cos(ang);
y = Alto+Radio*Math.sin(ang);
lineTo(x, y);
}
lineTo(Radio, AltoT);
for (ang=90*(Math.PI/180); ang<=180*(Math.PI/180); ang += vel) {
x = Radio+Radio*Math.cos(ang);
y = Alto+Radio*Math.sin(ang);
lineTo(x, y);
}
lineTo(0, Radio);
for (ang=180*(Math.PI/180); ang<=270*(Math.PI/180); ang += vel) {
x = Radio+Radio*Math.cos(ang);
y = Radio+Radio*Math.sin(ang);
lineTo(x, y);
}
endFill();
}
};
//
//Uso
//Nombre, Radio, AnchoT, AltoT, colorFondo, colorLinea, Trazo, Alfa, Prof
this.drawRectangle("mc", 4, 136, 16, 0xADBBBC, 0xADBBBC, 0, 10, 1);
Corrección 31/08/06: Había un error en el parámetro "Trazo" que impedía dibujar el trazo de la caja publicando en AS2.
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
draw,
MovieClip
Permite "rebobinar" un movieclip, reproduciendolo en sentido inverso.
Actionscript:
MovieClip.prototype.Reverse = function () {
if (this._currentframe>1) {
this.prevFrame();
} else {
delete this.onEnterFrame;
}
};
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
timeline,
MovieClip
Este prototipo permite realizar transiciones avanzadas de color, creando el efecto de foto quemada.
Actionscript:
MovieClip.prototype.picBurner = function(sentido:String) {
this.onEnterFrame = function() {
if (sentido == "out") {
if (this.n == undefined) {
this.n = 0;
}
if (this.n<256) {
this.n += 10;
} else {
delete this.onEnterFrame;
}
} else {
if (this.n == undefined) {
this.n = 256;
}
if (this.n>0) {
this.n -= 10;
} else {
delete this.onEnterFrame;
}
}
thisColor = {ra:100, rb:this.n, ga:100, gb:this.n, ba:100, bb:this.n, aa:256-this.n, ab:0};
col = new Color(this);
col.setTransform(thisColor);
};
};
//Uso
foto.picBurner("out");
foto2.picBurner("in");
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
efecto,
MovieClip
Prototipo de precarga de archivos externos. Indicandole un mc de destino, se encarga de crear en el mismo un holder para cargar la foto, una barra de precarga y un mc updater que se encarga del calculo. Esta es una versión reducida y personalizada del original, publicado en layer51
Actionscript:
MovieClip.prototype.preload = function(image, barWidth, imgWidth, imgHeight) {
var barWidth = barWidth == undefined ? 100 : barWidth;
var imgWidth = imgWidth == undefined ? 0 : imgWidth;
var imgHeight = imgHeight == undefined ? 0 : imgHeight;
this.createEmptyMovieClip("holder_mc", 0);
this.createEmptyMovieClip("updater_mc", 1);
this.createEmptyMovieClip("barra_mc", 2);
this.createEmptyMovieClip("filete_mc", 3);
this.barra_mc._xscale = 1;
with (this.barra_mc) {
beginFill(0x000000, 100);
lineTo(barWidth, 0);
lineTo(barWidth, 1);
lineTo(0, 1);
lineTo(0, 0);
}
with (this.filete_mc) {
//beginFill(0x000000, 100);
lineStyle(0, 0x0000);
lineTo(barWidth, 0);
lineTo(barWidth, 2);
lineTo(0, 2);
lineTo(0, 0);
}
if (imgWidth != 0) {
this.barra_mc._x = this.filete_mc._x=imgWidth/2-barWidth/2;
}
if (imgHeight != 0) {
this.filete_mc._y = imgHeight/2-this.filete_mc._height/2;
this.barra_mc._y = imgHeight/2-this.barra_mc._height/2+1;
}
this.holder_mc.loadMovie(image);
this.updater_mc.onEnterFrame = function() {
this.Loaded = this._parent.holder_mc.getBytesLoaded();
this.Total = this._parent.holder_mc.getBytesTotal();
this.Percent = Math.ceil((this.Loaded/this.Total)*100);
if (this.Loaded != this.Total || this.Total<=0) {
this.Percent = this.Total == 0 ? 0 : this.Percent;
this._parent.barra_mc._xscale = this.Percent;
trace(this.Percent+" %");
} else {
this._parent.barra_mc._xscale = this.Percent;
if (this.holder_mc._alpha>90) {
this.holder_mc._alpha = 100;
delete this.onEnterFrame;
} else {
this.holder_mc._alpha++;
}
this._parent.barra_mc.removeMovieClip();
this._parent.filete_mc.removeMovieClip();
this.removeMovieClip();
}
};
};
//Uso:
//image, barWidth, imgWidth, imgHeight
holder_mc.preload("http://www.bigwalls.de/Fotos/MontBlanc/Drus.jpg?"+random(99999), 60, 200, 200);
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
precarga
Genera un temblor en la cantidad definida por el parámetro value. Si se usa sin parámetros detiene el temblor.
Actionscript:
MovieClip.prototype.shake = function(value) {
if (value) {
this.orgX = this._x;
this.orgY = this._y;
this.onEnterFrame = function() {
this._x = this.orgX+Math.random()*(value*2)-value;
this._y = this.orgY+Math.random()*(value*2)-value;
};
} else {
delete this.onEnterFrame;
this._x = this.orgX;
this._y = this.orgY;
}
};
//Uso 1
obj_mc.shake(5);//provoca un temblor de 5 pixeles
//Uso 2
obj_mc.shake();//detiene temblor
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
efecto,
comportamiento,
shake,
MovieClip
Este prototipo calcula y devuelve la velocidad de movimiento del movieClip sobre el que se aplica (obj)
Actionscript:
MovieClip.prototype.getSpeed = function() {
this.momento = new Date();
this.t2 = this.momento.getTime();
if (!this.t1) {
this.t1 = this.momento.getTime();
}
this.t = this.t2-this.t1;
this.t1 = this.t2;
//
this.dx2 = this._x;
this.dy2 = this._y;
if (!this.dx1 || !this.dy1) {
this.dx1 = this.dx2;
this.dy1 = this.dy2;
}
this.dx = Math.abs(this.dx2-this.dx1);
this.dy = Math.abs(this.dy2-this.dy1);
this.d = Math.sqrt(this.dx*this.dx+this.dy*this.dy);
this.dx1 = this.dx2;
this.dy1 = this.dy2;
//
this.v = Math.ceil(this.d/this.t*10);
return this.v;
};
//Uso
obj.onPress = function() {
startDrag(this);
this.onEnterFrame = function() {
this.barra_mc._yscale = this.getSpeed();
};
};
obj.onRelease = mc.onReleaseOutside=function () {
stopDrag();
delete this.onEnterFrame;
};
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
velocidad,
MovieClip
Este prototipo crea una retícula de elementos, en base a un símbolo que se presupone existente en la librería y linkado con un identificador que se pasa en el parámetro
item. El alto y ancho de la retícula se define en los parámetros
anchogrid y
altogrid.
Descargable grid prototype
Actionscript:
MovieClip.prototype.grid = function(item, anchogrid, altogrid) {
var totalgrid:Number = anchogrid*altogrid;
for (i=0; i<totalgrid; i++) {
var escalon:Number = Math.floor(i/anchogrid);
var resetx:Number = i-(escalon*anchogrid);
var mc:MovieClip = this.attachMovie(item, "obj"+i, i);
var anchopatron:Number = mc._width;
var altopatron:Number = mc._height;
mc._x = (anchopatron*resetx);
mc._y = (escalon*altopatron);
}
};
//Uso
this.grid("obj", 7, 5);
//Presupone la existencia de un simbolo en la biblioteca linkado como "obj"
Enlaces relacionados: No related posts, | Tags:
prototipo,
actionscript,
grid,
MovieClip
Este prototipo lanza una alerta de javascript con el parámetro message. Es una ampliación del método de debug trace. Resulta especialmente útil cuando nos vemos obligados a probar la película en el navegador, porque resulte imposible probar determinadas funciones en el IDE de flash.
Actionscript:
MovieClip.prototype.alert = function(message) {
trace(message);
getURL("javascript:alert('flash alert>> "+message+"');");
};
//Uso:
alert("un trace en tu navegador");
Enlaces relacionados: No related posts, | Tags:
prototipo,
alert,
trace,
navegador,
javascript,
actionscript,
MovieClip
Este prototipo abre enlaces en una nueva ventana de navegador, de tipo popup.
Usar con precaución, los actuales popup stopper de los navegadores pueden bloquear su funcionamiento.
Actionscript:
MovieClip.prototype.popUp = function(url, title, features) {
getURL("javascript:void(window.open('"+url+"','"+title+"','"+features+"'));");
};
//Uso:
this.popUp("http://drusunlimited.com","popUp name", "width=200, height=150");
Enlaces relacionados: No related posts, | Tags:
prototipo,
popup,
window,
navegador,
javascript,
actionscript,
MovieClip
Calcula la distancia ente dos puntos, devolviendo la hipotenusa.
Actionscript:
MovieClip.prototype.distance = function(x1, y1, x2, y2) {
var distance:Object = new Object();
distance.distx = x2-x1;
distance.disty = y2-y1;
distance.distance = Math.sqrt((distance.distx*distance.distx)+(distance.disty*distance.disty));
return distance;
};
//Uso:
_root.onMouseDown=function(){
distancia=this.distance(obj_mc._x, obj_mc._y, _xmouse, _ymouse);
trace(distancia.distance);
}
Aplicado sobre un movieClip, este rehuye el mouse, en función de la distancia especificada en el parámetro distance.
Actionscript:
MovieClip.prototype.avoidMouse = function(distance, speed, accel) {
distx = this._parent._xmouse-this._x;
disty = this._parent._ymouse-this._y;
distanceh = Math.sqrt((distx*distx)+(disty*disty));
if (distanceh<distance) {
var angle = Math.atan2(disty, distx);
if (accel) {
speed = Math.min(speed, accel*distance/distance);
}
this._x -= Math.cos(angle)*speed;
this._y -= Math.sin(angle)*speed;
}
};
//Uso:
obj_mc.onEnterFrame = function() {
this.avoidMouse(100, 10, 10);
};
Enlaces relacionados: No related posts, | Tags:
prototipo,
comportamiento,
actionscript,
MovieClip
Este prototipo produce un temblor en la ventana del navegador, la cantidad de veces indicadas en el parámetro amount
Actionscript:
MovieClip.prototype.shakeWin = function(amount:Number):Void {
getURL("javascript:function shakewin(n){if(parent.moveBy){for(i = 10;i> 0;i--){for(j = n;j> 0;j--){parent.moveBy(0,i);parent.moveBy(i,0);parent.moveBy(0,-i);parent.moveBy(-i,0);}}}};shakewin("+amount+");void(0)");
};
//Uso
this.shakeWin(5);
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
navegador,
javascript,
window,
MovieClip
Prototipo pausa, "made by drus" produce una detención de la timeline que lo invoca durante los milisegundos establecidos, una vez superados continúa con la reproducción.
Actionscript:
MovieClip.prototype.pausa = function(ms) {
var este = this;
este.stop();
var id = setInterval(function () {
clearInterval(id);
este.play();
}, ms);
};
//Uso
this.pausa(2000);
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
timeline,
pausa,
MovieClip
Código de movimiento parabólico, generosamente publicado por Eliseo en After hours
Actionscript:
_root.onMouseDown = function() {
mimc.x0 = mimc._x;
mimc.y0 = mimc._y;
mimc.t1 = 30;
mimc.x1 = _xmouse;
mimc.y1 = _ymouse;
g = 2;
mimc.t = 0;
mimc.vx0 = (mimc.x1-mimc.x0)/mimc.t1;
mimc.vy0 = (mimc.y1-mimc.y0-g*mimc.t1*mimc.t1/2)/mimc.t1;
mimc.onEnterFrame = function() {
this._x = this.x0+this.t*this.vx0;
this._y = this.y0+this.t*this.vy0+g*this.t*this.t/2;
if (this.t == this.t1) {
delete this.onEnterFrame;
} else {
this.t++;
}
};
};
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
comportamiento
Prototipo "made by drus" para hacer parpadear un movieClip.
Actionscript:
MovieClip.prototype.blink = function(veces, vel, fin) {
obj = this;
obj.n = obj._visible;
obj.cont = 0;
vel == undefined ? obj.vel=100 : obj.vel=vel;
this.id = setInterval(function () {
obj.cont += 1;
if (obj.cont<=veces*2) {
obj._visible = !obj._visible;
} else {
if (fin == undefined) {
fin = true;
}
obj._visible = fin;
clearInterval(obj.id);
}
}, this.vel);
};
Prototipo extraido de layer51 y modificado para admitir etiquetas HTML.
Imita el estupendo efecto de texto de group94 de construcción de texto letra a letra, con variaciones aleatorias.
Actionscript:
TextField.prototype.flipTo = function(s, rot) {
if (s == undefined) {
s = "";
}
if (this.text == "") {
this.text = " ";
}
var T = this._parent.createEmptyMovieClip(this._name+"_typer", this._parent.getNextHighestDepth());
T.txt = s;
T.rot = rot == undefined ? 0 : rot;
T.targ = this;
T.oldtxt = this.text;
for (var i = 0; i<T.oldtxt.length; i++) {
if (T.oldtxt.charAt(i) != T.txt.charAt(i)) {
T.backto = i;
break;
}
}
T.dir = -1;
T.count = 0;
T.onEnterFrame = function() {
if (this.L == undefined) {
this.L = this.targ.text.length;
}
if (++this.count>this.rot) {
this.L = this.L+T.dir;
this.count = 0;
}
var rndchar = chr(48+Math.random()*74);
if (this.dir<1) {
if (this.L>T.backto) {
this.targ.htmlText = this.targ.text.substr(0, this.L-1)+rndchar;
} else {
this.dir = 1;
}
} else {
if (this.L<=this.txt.length) {
if (this.txt.charAt(this.L-1) == "<") {
var LT = this.L;
for (var i = 0; i<this.txt.length; i++) {
if (this.txt.charAt(i) == ">") {
this.L = i+1;
var tmp = this.txt.substr(0, this.L);
this.targ.htmlText = tmp;
break;
}
}
this.targ.htmlText = this.txt.substr(0, this.L-1);
} else {
this.targ.htmlText = this.txt.substr(0, this.L-1)+rndchar;
}
} else {
this.targ.htmlText = this.txt;
this.onEnterFrame = undefined;
this.removeMovieClip();
}
}
};
};
Prototipo "made by drus", este efecto de texto deconstruye una cadena en palabras y contruye parrafos de acuerdo al tamaño deseado.
El hecho de deconstruir permite aplicar efectos a cada palabra.
Actionscript:
mytext = 'Lorem ipsum te pro utinam volutpat. An mundi putant eam, nam ad soluta aliquid cotidieque, no nam nominavi repudiandae. Eum ne vero accusam expetenda. Velit takimata consulatu no eos';
//
String.prototype.deconstruct = function(mc, ancho) {
var words:Array = new Array();
var words = this.split(" ");
var espaciado = 5;
var interlineado = 20;
var column = ancho;
var n = 0;
for (var i=0; i<words .length; i++) {
var word:MovieClip = mc.createEmptyMovieClip("word_el"+i, i);
if (i>0) {
mix += mc["word_el"+(i-1)]._width+espaciado;
} else {
var mix = 0;
}
if (mix>column) {
var mix = 0;
n++;
var miy = n*interlineado;
}
word._x = mix;
word._y = miy;
word.createTextField("field", i, 0, 0, 4, 4);
word.field.autoSize = "left";
word.field.border = false;
word.field.selectable = false;
word.field.text = words[i];
}
};
//Uso
_root.createEmptyMovieClip("parrafo",1);
mytext1.deconstruct(parrafo, 150);
Prototipo "made by drus", efecto de texto creado para aplicar negritas en fuentes pixeladas como la standard.
Debemos tener las fuentes linkadas en la librería.
Actionscript:
String.prototype.toBold = function() {
var tmp_txt:String=this.split("<b>").join("<font face='bold'>");
tmp_txt=tmp_txt.split("</b>").join("</font>");
return tmp_txt;
};
mytext = "<b>Lorem ipsum dolor sit amet</b>, consectetuer adipiscing elit. In <b>sagittis</b> quam et nibh. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Cras adipiscing iaculis orci. Suspendisse potenti. In elementum varius nunc. Proin accumsan arcu et massa. Quisque eu eros in turpis molestie dapibus. Aliquam erat volutpat. Donec erat purus, tristique congue, pretium vitae, volutpat eu, justo. Phasellus porttitor. Etiam et metus nec nunc egestas euismod. Suspendisse a purus. Proin laoreet leo at enim. Quisque risus. Vivamus pede. Duis quis velit. Quisque in urna. <b>Fusce elementum</b> diam vitae tellus. Vestibulum vehicula dui sed tellus.";
//Uso
txt.htmlText=mytext.toBold();
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
efecto,
texto,
String
Prototipo "made by drus" para dar a cualquier movieClip propiedades de icono: drag&drop, dobleclick...
Actionscript:
MovieClip.prototype.icono = function(milabel, handler) {
_global.icoDepth=0;
this.useHandCursor = false;
this.onPress = function() {
_global.icoDepth++;
this.swapDepths(_global.icoDepth);
startDrag(this);
this.time = new Date();
this.clickTimeb = this.time.getTime();
this.doubleClick = (this.clickTimeb-this.clickTimea);
if (this.doubleClick<400) {
handler(milabel);
}
this.clickTimea = this.time.getTime();
};
this.onRelease = this.onReleaseOutside=function () {
stopDrag();
};
var label_fm:TextFormat = new TextFormat();
label_fm.align = "center";
label_fm.font = "_sans";
label_fm.size = 10;
this.createTextField("label_txt", 1, -10, 0, 20, 30);
this.label_txt.autoSize = "center";
//this.label_txt.border = true;
this.label_txt.text = milabel;
this.label_txt.setTextFormat(label_fm);
};
//Uso:
handlerFunction = function (cual) {
trace("dobleClick "+cual);
};
ico_misdocs_mc.icono("Mis documentos", handlerFunction);
ico_papelera_mc.icono("Papelera", handlerFunction);
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
comportamiento,
MovieClip
Prototipo para recrear el efecto de texto de group94 en el que van apareciendo los carácteres de la cadena input desde el último al primero.
Publicado en After-hours
Actionscript:
TextField.
prototype.
textoFx =
function(input
){
var obj =
this;
obj.
htmlText =
"";
var mi_level =
random(500)+
500;
var mc =
this.
_parent.
createEmptyMovieClip("loop", mi_level
);
var input =
String(input
).
split(" ");
mc.
onEnterFrame =
function() {
obj.
htmlText = input.
pop()+
" "+obj.
htmlText;
if (!input.
length) {
delete mc.
onEnterFrame;
removeMovieClip(mc
);
}
};
};
//Uso
textarea.textoFx("Nulla ac justo. Integer mauris. Aliquam consectetuer libero at nulla. Phasellus at purus vitae nisi porttitor aliquam. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec dignissim tellus imperdiet lorem. Nunc hendrerit consectetuer elit. Donec ullamcorper orci. In pellentesque, neque pellentesque porta consectetuer, dui odio venenatis orci, id vulputate arcu dui vel mauris. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Vestibulum eget nibh non ipsum tempus consectetuer.");
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
efecto,
texto,
TextField
Prototipo de Kaax, publicado generosamente en After-hours
Actionscript:
import flash.filters.BlurFilter;
MovieClip.prototype.blurTo = function(x, y, speed, blurX, blurY, calidadBlur) {
this.onEnterFrame = function() {
if (Math.round(this._x) == Math.round(x) && Math.round(this._y) == Math.round(y)) {
blurToParando = new BlurFilter(0, 0, 0);
this._x = Math.round(this._x);
this._y = Math.round(this._y);
this.filters = [blurToParando];
delete this.onEnterFrame;
} else {
blurTo = new BlurFilter(blurX--, blurY--, calidadBlur);
this._x -= (this._x-x)*speed;
this._y -= (this._y-y)*speed;
this.filters = [blurTo];
}
};
};
//Uso:
mc.blurTo(523, 434, .1, 50, 50, 4);
Enlaces relacionados: No related posts, | Tags:
actionscript,
prototipo,
efecto,
blur,
MovieClip
—
Siguiente página »