Follow me @Tmeister

Archive for the ‘ActionScript’ Category

Acceder el Stage desde cualquier clase AS3

Posted by Tmeister On November - 13 - 2008

Al trabajar con clases AS3 en nuestros proyectos hay ocasiones en los que debemos acceder al stage principal de nuestra aplicación desde clases que no extienden a “DisplayObject”, haciendo que debamos pasar como parámetro dicho stage a las clases, esto funciona pero en realidad es un poco “sucio”.

Una solución simple es crear una clase singleton, en la cual, podemos almacenar no solo el stage principal, sino cualquier otro valor que necesitemos en varias clases. Algo así como _global de AS2, lo recuerdan?
Aquí la clase

[as]
package net.tmeister.utils
{
public dynamic class Global
{
private static var global : Global

public static function getInstance() : Global
{
if ( global == null )
{
global = new Global( arguments.callee );
}
return global;
}

public function Global( caller : Function = null )
{
if ( caller != Global.getInstance )
{
throw new Error (“Global is a singleton class, use getInstance() instead”);
}
if ( Global.global != null )
{
throw new Error( “Only one Global instance should be instantiated” );
}
}
}
}
[/as]

Y su modo de uso.

[as]
package
{
import flash.display.MovieClip;
import net.tmeister.utils.Global
public class Main extends MovieClip
{
private var global:Global;

public function Main()
{
global = Global.getInstance();
global.stage = stage
trace(‘global.stage’ + global.stage)
global.algunOtroValor = new MovieClip()
trace(‘global.algunOtroValor ‘ + global.algunOtroValor)
}
}
}
[/as]

Simple.

Habemus Flash Player 10 !!

Posted by Tmeister On October - 15 - 2008

Ya está disponible para su descarga la versión 10 de nuestro querido Flash Player, entre las características principales podemos encontrar:

  • Efectos 3D Nativos
  • Filtros y efectos personalizados
  • Soporte de texto avanzado
  • Generación de sonido dinámico
  • Nuevo API de dibujo
  • Aceleración por hardware
  • Nuevo DataType Vector
  • Streaming dinámico

Y más más…. Ahora solo falta esperar el release de FLASH CS4 :)

La información completa la pueden encontrar en la página oficial del FlashPlayer

Flash CS4, A la vuelta de la esquina.

Posted by Tmeister On October - 10 - 2008

Como ya sabrán, la nueva suite de Adobe esta por ser lanzada, y para abrir boca, la documentación ya esta disponible.

Main help portal
http://help.adobe.com/en_US/Flash/10.0_Welcome/

New features
http://help.adobe.com/en_US/…html

Programming ActionScript 3.0
http://help.adobe.com/…./

ActionScript 3.0 Language and Components Reference
http://help.adobe.com/en_US/AS3LCR/Flash_10.0/index.html

Extending Adobe Flash Professional CS4
http://help.adobe.com/…/index.html

Con esto, sin duda, ya tenemos para entretenernos un bien tiempo.

Clase TiledBackground

Posted by Tmeister On July - 4 - 2008

Que tal gente.

Hace un buen rato que no posteo, pero aquí estoy de vuelta con algo sencillo.
TiledBackground es una clase simple la cual toma una imagen externa (jpg, gif, png) y la repite tantas veces quepa en el navegador tal y como lo hiciéramos en CSS :)

Además de que tiene un par de parámetros, se puede sobreponer un gradiente radial para hacer un efecto sobre el fondo. Los colores y alphas del gradiente se pueden configurar.

TiledBackground
[as]
package net.tmeister.utils.background
{

import flash.display.BitmapData;
import flash.display.Loader;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.geom.Matrix;
import flash.net.URLRequest;
import flash.display.StageScaleMode;
import flash.display.StageAlign;
import flash.display.GradientType;

public class TiledBackground extends Sprite
{
private var _pattern:String;
private var _container:Sprite;
private var _image:Loader;
private var _stage:Stage;
private var _gradient:Boolean = true;
private var _gProperties:Object = {};

public function TiledBackground(stage:Stage)
{
_stage = stage
_stage.scaleMode = StageScaleMode.NO_SCALE;
_stage.align = StageAlign.TOP_LEFT;
_stage.addEventListener(Event.RESIZE, resize);
}
public function set pattern (urlPattern:String):void
{
_pattern = urlPattern;
loadPattern();
}
public function get pattern():String
{
return _pattern;
}
public function set radialGradient(value:Boolean):void
{
_gradient = value;
}
public function get radialGradient():Boolean
{
return _gradient;
}
public function set gradientProperties(properties:Object):void
{
_gProperties = properties;
}
public function get gradientProperties():Object
{
return _gProperties;
}
private function loadPattern():void
{
var patternLoader:Loader = new Loader();
var patternUrl:URLRequest = new URLRequest(_pattern);
patternLoader.load(patternUrl);
patternLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onPatternLoaded);
}
private function onPatternLoaded(e:Event):void
{
_image = e.target.loader;
createBackground();
createRadialGradient()
}
private function createBackground():void
{
if (_container != null)
{
removeChild(_container);
_container = null;
}
var bitmap:BitmapData = new BitmapData (_image.width, _image.height);
bitmap.draw(_image)
_container = new Sprite();
_container.graphics.beginBitmapFill(bitmap);
_container.graphics.drawRect(0,0, _stage.stageWidth , _stage.stageHeight);
_container.graphics.endFill();
addChild(_container);
}

private function createRadialGradient():void
{
if (! _gradient )
{
return;
}
var matrix:Matrix = new Matrix();
var gType:String = GradientType.RADIAL;
matrix.createGradientBox(_stage.stageWidth,_stage.stageHeight,0,0,0);
var gColors:Array = [(_gProperties.insideColor) ? _gProperties.insideColor : 0xffffff, (_gProperties.outsideColor) ? _gProperties.outsideColor : 0xffffff];
var gAlphas:Array = [(_gProperties.insideColorAlpha) ? _gProperties.insideColorAlpha : .15 ,(_gProperties.outsideColorAlpha) ? _gProperties.outsideColorAlpha : 0];
var gRatio:Array = [0,255];
var bound:Sprite = new Sprite();
bound.graphics.beginGradientFill(gType,gColors,gAlphas,gRatio,matrix);
bound.graphics.drawRect(0,0,_stage.stageWidth,_stage.stageHeight);
addChild(bound);
}
private function resize(e:Event):void
{
createBackground();
createRadialGradient()
}
}
}
[/as]
Uso:

[as]
package
{
import flash.display.Sprite;
import net.tmeister.utils.background.TiledBackground

public class sampleTiled extends Sprite
{
public function sampleTiled()
{
var background:TiledBackground = new TiledBackground(stage);
background.pattern = “bg1.gif”
background.gradientProperties = {insideColor:0xffffff, outsideColor:0xffffff, insideColorAlpha:.05, outsideColorAlpha:0}
addChild(background)
}
}
}
[/as]

Aquí el ejemplo y como siempre los archivos fuente están disponibles.

Archivos para descarga

download

Download: TiledBackground.zip
Version: 0.1
Updated: July 4, 2008
Size: 12.42 KB

Saludos!!

Obteniendo los hijos de un DisplayObject [AS3]

Posted by Tmeister On April - 1 - 2008

Está en una clase simple pero muy útil, al menos para mí, que recorre todos los hijos contenidos en un DisplayObject, la clase cuenta con 2 funciones:

getAllChilds

Regresa todos los hijos contenidos en el “target”

getChildsByType

Regresa solo los hijos que sean de un tipo específico, por ejemplo solo MovieClips, o solo Botones.

DisplayObjectUtils

[as]
package net.tmeister.utils
{
/**
* @author Enrique Chavez aka Tmeister
*/
import flash.display.DisplayObject;
public class DisplayObjectUtils
{
/**
*
* @param target
* @return Array
*/
public static function getAllChilds(target:*):Array
{
var listTmp:Array = []
for (var a = 0; a < target.numChildren; a++ )
{
listTmp.push (target.getChildAt(a) )
}
return listTmp
}
/**
*
* @param target
* @param type
* @return
*/
public static function getChildsByType(target:*, type:*):Array
{
var listTmp:Array = []
for (var a = 0; a < target.numChildren; a++ )
{
if (target.getChildAt(a) is type)
{
listTmp.push (target.getChildAt(a) )
}
}
return listTmp
}
}
}
[/as]

Su uso es el siguiente:

Primero creamos unos Movieclips y unos botones para tener algo que buscar.

[as]
import net.tmeister.utils.DisplayObjectUtils;
import fl.controls.Button

createMovieClips()
createButtons()
getChilds()

function createButtons()
{
for(var a:Number = 0; a<2; a++)
{
var tmp:Button = new Button();
tmp.x = Math.random()*400
tmp.y = Math.random()*400
tmp.label = “buton”+a
addChild(tmp)
}
}
function createMovieClips()
{
for(var a:Number = 0; a<5; a++)
{
var tmp:MovieClip = new MovieClip();
tmp.graphics.beginFill(0x2a2a2a, .5)
tmp.graphics.drawRect(Math.random()*500, Math.random()*300, Math.random()*100, Math.random()*100);
tmp.graphics.endFill();
tmp.name = “mc”+a;
addChild(tmp)
}
}
function getChilds()
{
trace(“All Childs: ” + DisplayObjectUtils.getAllChilds(this) )
trace(“=====================================================================================”)
trace(“Movieclips: ” + DisplayObjectUtils.getChildsByType(this, MovieClip))
trace(“=====================================================================================”)
trace(“Buttons: ” + DisplayObjectUtils.getChildsByType(this, Button))

}

[/as]

Acerca de mi
Enrique Chavez

Enrique Chávez también es conocido como @Tmeister es un desarrollador, emprendedor, poeta y loco.

Geek autodeclarado y apasionado de todo lo que tiene que ver con tecnología y desarrollo.

Cuenta con una experiencia de más de 7 años en el ramo del desarrollo, creando, sobre todo, aplicaciones web en la empresa Sapotek.

A finales del 2008 crea, junto con 3 colegas, la consultoría llamada AureaCode, enfocándose a brindar servicios de desarrollo web en todas sus variantes.

Si necesitas algún tipo de información o consulta por favor no dude en escribir.

View Enrique Chávez's profile on LinkedIn

Carlos Enrique Chavez Garcia's VisualCV

RSS Feed

Links Patrocinados