SimpleButton Not Displaying - actionscript-3

I'm just trying to get a SimpleButton to appear on the stage in an AS3 project. For some reason, it won't appear. Can anyone see why?
Thanks in advance.
Code:
//Main class:
package
{
import flash.display.Sprite;
import view.controls.CustomButton;
import view.controls.Button;
public class ButtonTest extends Sprite
{
//private var myCustomButton:Button = new Button();
private var myCustomButton:CustomButton;
public function ButtonTest()
{
myCustomButton = new CustomButton("Hello", 0xFF0000);
addChild(myCustomButton);
}
}
}
//Custom Button Class:
package view.controls
{
import flash.display.GradientType;
import flash.display.SimpleButton;
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
import flash.geom.Matrix;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
public class CustomButton extends Sprite
{
private var textColor:uint = 0x000000;
private var myColor:uint = 0xFF0000;
private var btnWidth:Number = 30;
private var btnHeight:Number = 18;
public function CustomButton(buttonText:String, gradientColor:uint)
{
var colors:Array = new Array();
var alphas:Array = new Array(1, 1);
var ratios:Array = new Array(0, 255);
var gradientMatrix:Matrix = new Matrix();
var myColor:uint = 0xFF0000;
gradientMatrix.createGradientBox(btnWidth, btnHeight, Math.PI/2, 0, 0);
//
var ellipseSize:int = 2;
var btnUpState:Sprite = new Sprite();
colors = [0xFFFFFF, myColor];
btnUpState.graphics.lineStyle(3, brightencolor(myColor, -50));
btnUpState.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, gradientMatrix);
btnUpState.graphics.drawRoundRect(0, 0, btnWidth, btnHeight, ellipseSize, ellipseSize);
btnUpState.addChild(createButtonTextField(buttonText, textColor));
//
var btnOverState:Sprite = new Sprite();
colors = [0xFFFFFF, brightencolor(myColor, 50)];
btnOverState.graphics.lineStyle(1, brightencolor(myColor, -50));
btnOverState.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, gradientMatrix);
btnOverState.graphics.drawRoundRect(0, 0, btnWidth, btnHeight, ellipseSize, ellipseSize);
btnOverState.addChild(createButtonTextField(buttonText, textColor))
//
var btnDownState:Sprite = new Sprite();
colors = [brightencolor(myColor, -15), brightencolor(myColor, 50)];
btnDownState.graphics.lineStyle(1, brightencolor(myColor, -50));
btnDownState.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, gradientMatrix);
btnDownState.graphics.drawRoundRect(0, 0, btnWidth, btnHeight, ellipseSize, ellipseSize);
btnDownState.addChild(createButtonTextField(buttonText, textColor))
//
var myButton:SimpleButton = new SimpleButton(btnUpState, btnOverState, btnDownState, btnOverState);
myButton.name = buttonText;
myButton.height = btnHeight;
myButton.width = btnWidth;
}
private function createButtonTextField(Text:String, textcolor:uint):TextField {
var myTextField:TextField = new TextField();
myTextField.textColor = textcolor;
myTextField.selectable = false;
myTextField.width = btnWidth;
myTextField.height = btnHeight;
var myTextFormat:TextFormat = new TextFormat();
myTextFormat.align = TextFormatAlign.CENTER;
myTextField.defaultTextFormat = myTextFormat;
Text = "<b>"+Text+"</b>";
myTextField.htmlText = '<font face="Arial">'+Text+'</font>';
myTextField.x = (btnWidth/2)-(myTextField.width/2);
return myTextField;
}
private function brightencolor(color:int, modifier:int):int {
var hex:Array = hexToRGB(color);
var red:int = keepInBounds(hex[0]+modifier);
var green:int = keepInBounds(hex[1]+modifier);
var blue:int = keepInBounds(hex[2]+modifier);
return RGBToHex(red, green, blue);
}
private function hexToRGB (hex:uint):Array {
var colors:Array = new Array();
colors.push(hex >> 16);
var temp:uint = hex ^ colors[0] << 16;
colors.push(temp >> 8);
colors.push(temp ^ colors[1] << 8);
return colors;
}
private function keepInBounds(number:int):int {
if (number < 0) number = 0;
if (number > 255) number = 255;
return number;
}
private function RGBToHex(uR:int, uG:int, uB:int):int {
var uColor:uint;
uColor = (uR & 255) << 16;
uColor += (uG & 255) << 8;
uColor += (uB & 255);
return uColor;
}
}
}

You need to add the created SimpleButton object myButton to the CustomButton's display list:
// ...
var myButton:SimpleButton = new SimpleButton(btnUpState, btnOverState, btnDownState, btnOverState);
myButton.name = buttonText;
myButton.height = btnHeight;
myButton.width = btnWidth;
addChild( myButton );
}
Although in your case, maybe you should think about making the CustomButton extend the SimpleButton instead.

Related

How to scale GraphicsPathCommand data?

Context: For a legacy Flex/Actionscript drawing app, I need to add scaling of simple symbols. The app uses the Graffiti lib for drawing and the resulting shape data is stored as GraphicsPathCommands serialized to XML using the Degrafa lib for save and reload. I need to enable the user to scale these graphics and then get updated path data which can be serialized. The symbols are simple but more complicated than simple geometry. For example:
Question: I converted the SVG data for this symbol to Actionscript GraphicsPathCommands and am able to draw it, and of course translation is easy – but I don't know how I would scale it, given a bounding box defined by a user dragging out a marquee rectangle in the app.
Does anyone know of either an Actionscript way of transforming the command data, or a Javascript snippet for scaling SVG which I can port to Actionscript?
For reference, an example of the Actionscript GraphicsPathCommands for drawing a star is below.
public function DrawPathExample()
{
var star_commands:Vector.<int> = new Vector.<int>(5, true);
star_commands[0] = GraphicsPathCommand.MOVE_TO;
star_commands[1] = GraphicsPathCommand.LINE_TO;
star_commands[2] = GraphicsPathCommand.LINE_TO;
star_commands[3] = GraphicsPathCommand.LINE_TO;
star_commands[4] = GraphicsPathCommand.LINE_TO;
var star_coord:Vector.<Number> = new Vector.<Number>(10, true);
star_coord[0] = 66; //x
star_coord[1] = 10; //y
star_coord[2] = 23;
star_coord[3] = 127;
star_coord[4] = 122;
star_coord[5] = 50;
star_coord[6] = 10;
star_coord[7] = 49;
star_coord[8] = 109;
star_coord[9] = 127;
graphics.beginFill(0x003366);
graphics.drawPath(star_commands, star_coord);
}
Solution
A full solution for interactively scaling GraphicsPathCommand data is below. The path data was derived from an SVG put through this SVGParser. It generates path drawing commands in the form of graphics.lineTo(28.4,16.8);. A couple of utility functions separate the data from the commands and store them in Vectors so the data can be serialized. I don't need to use arbitrary SWGs so I just hardcoded the data.
package classes
{
import flash.display.GraphicsPathCommand;
import flash.display.Shape;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.geom.Rectangle;
public class DrawSVG extends Sprite
{
private var startPt:Point = new Point();
private var selectRect:Rectangle = new Rectangle();
private var viewBox:Rectangle = new Rectangle();
protected var commands:Vector.<int> = new Vector.<int>();
protected var drawingData:Vector.<Number> = new Vector.<Number>();
protected var sourceDrawingData:Vector.<Number> = new Vector.<Number>();
public function DrawSVG()
{
super();
this.addEventListener(Event.ADDED_TO_STAGE, setup);
setupWomanData();
}
private function setup(event:Event):void
{
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
}
private function onMouseDown(event:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
this.graphics.clear();
// offset so graphic draws centered on click point
startPt = new Point(event.stageX - (viewBox.width /2), event.stageY - (viewBox.height /2));
selectRect = new Rectangle(startPt.x, startPt.y, viewBox.width, viewBox.height);
var kx:Number = selectRect.width / (viewBox.width);
var ky:Number = selectRect.height / (viewBox.height);
var scaleFactor:Number = kx < ky ? kx : ky;
drawSymbol(scaleFactor);
this.graphics.lineStyle(1, 0x000000);
this.graphics.drawRect(selectRect.x, selectRect.y, selectRect.width, selectRect.height);
}
private function onMouseMove(event:MouseEvent):void
{
selectRect.width = Math.max(viewBox.width, Math.abs(event.stageX - startPt.x));
selectRect.height = Math.max(viewBox.height, Math.abs(event.stageY - startPt.y));
var kx:Number = selectRect.width / (viewBox.width);
var ky:Number = selectRect.height / (viewBox.height);
var scaleFactor:Number = kx < ky ? kx : ky;
this.graphics.clear();
drawSymbol(scaleFactor);
this.graphics.lineStyle(1, 0x000000);
this.graphics.drawRect(selectRect.x, selectRect.y, viewBox.width * scaleFactor, viewBox.height * scaleFactor);
}
private function onMouseUp(event:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
this.graphics.clear();
createSprite(commands, drawingData);
}
private function drawSymbol(toScale:Number):void
{
drawingData.length = 0;
for (var i:int = 0; i < sourceDrawingData.length; i++) {
drawingData[i] = Math.max(sourceDrawingData[i], sourceDrawingData[i] * toScale);
drawingData[i] += i % 2 == 0 ? startPt.x : startPt.y ;
}
this.graphics.clear();
this.graphics.lineStyle();
this.graphics.beginFill(0xff0000);
this.graphics.drawPath(commands, drawingData);
this.graphics.endFill();
}
private function createSprite(command:Vector.<int>, coord:Vector.<Number>):Shape{
var s:Shape = new Shape();
addChild(s);
s.graphics.beginFill(0xff);
s.graphics.drawPath(command, coord);
s.graphics.endFill();
return s;
}
private function setupWomanData():void
{
commands = new Vector.<int>();
drawingData = new Vector.<Number>();
viewBox= new Rectangle(0, 0, 24.629, 52.336);
addMoveToCmd(12.31,10.3);
addCurveToCmd(13.37,10.3,14.3,9.89);
addCurveToCmd(15.24,9.48,15.94,8.78);
addCurveToCmd(16.64,8.08,17.05,7.14);
addCurveToCmd(17.46,6.2,17.46,5.15);
addCurveToCmd(17.46,4.1,17.05,3.16);
addCurveToCmd(16.64,2.23,15.94,1.52);
addCurveToCmd(15.24,0.82,14.3,0.41);
addCurveToCmd(13.37,0,12.31,0);
addCurveToCmd(11.26,0,10.33,0.41);
addCurveToCmd(9.39,0.82,8.69,1.52);
addCurveToCmd(7.98,2.23,7.57,3.16);
addCurveToCmd(7.16,4.1,7.16,5.15);
addCurveToCmd(7.16,6.2,7.57,7.14);
addCurveToCmd(7.98,8.08,8.69,8.78);
addCurveToCmd(9.39,9.48,10.33,9.89);
addCurveToCmd(11.26,10.3,12.31,10.3);
addLineToCmd(12.314,10.304);
addMoveToCmd(24.6,26.36);
addLineToCmd(20.7,12.77);
addCurveToCmd(20.62,12.3,20.39,11.91);
addCurveToCmd(20.15,11.51,19.81,11.23);
addCurveToCmd(19.47,10.94,19.04,10.78);
addCurveToCmd(18.61,10.62,18.14,10.62);
addLineToCmd(6.49,10.62);
addCurveToCmd(6.02,10.62,5.59,10.78);
addCurveToCmd(5.16,10.94,4.82,11.23);
addCurveToCmd(4.48,11.51,4.24,11.91);
addCurveToCmd(4.01,12.3,3.93,12.77);
addLineToCmd(0.03,26.36);
addCurveToCmd(0.01,26.4,0.01,26.45);
addCurveToCmd(-0.01,26.5,-0.01,26.55);
addCurveToCmd(0.01,26.6,0.01,26.65);
addCurveToCmd(0.02,26.69,0.03,26.74);
addCurveToCmd(-0.15,27.95,0.55,28.69);
addCurveToCmd(1.25,29.44,2.2,29.6);
addCurveToCmd(3.15,29.77,4.05,29.3);
addCurveToCmd(4.95,28.84,5.17,27.63);
addLineToCmd(6.85,21.37);
addLineToCmd(4.07,34.88);
addCurveToCmd(3.81,35.51,3.91,36.15);
addCurveToCmd(4,36.78,4.35,37.3);
addCurveToCmd(4.7,37.81,5.26,38.13);
addCurveToCmd(5.81,38.45,6.49,38.45);
addLineToCmd(6.78,38.45);
addLineToCmd(6.78,49.72);
addCurveToCmd(6.78,50.99,7.59,51.62);
addCurveToCmd(8.41,52.25,9.39,52.25);
addCurveToCmd(10.37,52.25,11.19,51.62);
addCurveToCmd(12,50.99,12,49.72);
addLineToCmd(12,38.45);
addLineToCmd(12.63,38.45);
addLineToCmd(12.63,49.72);
addCurveToCmd(12.63,50.99,13.44,51.62);
addCurveToCmd(14.26,52.25,15.24,52.25);
addCurveToCmd(16.22,52.25,17.04,51.62);
addCurveToCmd(17.85,50.99,17.85,49.72);
addLineToCmd(17.85,38.45);
addLineToCmd(18.14,38.45);
addCurveToCmd(18.82,38.45,19.38,38.13);
addCurveToCmd(19.93,37.81,20.28,37.3);
addCurveToCmd(20.63,36.78,20.72,36.14);
addCurveToCmd(20.81,35.51,20.56,34.87);
addLineToCmd(17.78,21.37);
addLineToCmd(19.45,27.58);
addCurveToCmd(19.67,28.79,20.57,29.27);
addCurveToCmd(21.47,29.75,22.43,29.6);
addCurveToCmd(23.38,29.45,24.08,28.7);
addCurveToCmd(24.78,27.96,24.6,26.74);
addCurveToCmd(24.61,26.69,24.62,26.65);
addCurveToCmd(24.63,26.6,24.63,26.55);
addCurveToCmd(24.63,26.5,24.62,26.45);
addCurveToCmd(24.62,26.4,24.6,26.36);
addLineToCmd(24.601,26.356);
}
protected function addCurveToCmd(p1:Number, p2:Number, p3:Number, p4:Number):void
{
commands.push(GraphicsPathCommand.CURVE_TO);
sourceDrawingData.push(p1);
sourceDrawingData.push(p2);
sourceDrawingData.push(p3);
sourceDrawingData.push(p4);
}
protected function addMoveToCmd(p1:Number, p2:Number):void
{
commands.push(GraphicsPathCommand.MOVE_TO);
sourceDrawingData.push(p1);
sourceDrawingData.push(p2);
}
protected function addLineToCmd(p1:Number, p2:Number):void
{
commands.push(GraphicsPathCommand.LINE_TO);
sourceDrawingData.push(p1);
sourceDrawingData.push(p2);
}
}
}
Seems like there is a pretty straightforward way to do this. It looks like the only thing to scale are the coordinates themselves, so you may just apply a scale factor.
Based on your example:
public function ASEntryPoint() {
var star_commands:Vector.<int> = new Vector.<int>(5, true);
star_commands[0] = GraphicsPathCommand.MOVE_TO;
star_commands[1] = GraphicsPathCommand.LINE_TO;
star_commands[2] = GraphicsPathCommand.LINE_TO;
star_commands[3] = GraphicsPathCommand.LINE_TO;
star_commands[4] = GraphicsPathCommand.LINE_TO;
var star_coord:Vector.<Number> = new Vector.<Number>(10, true);
star_coord[0] = 66; //x
star_coord[1] = 10; //y
star_coord[2] = 23;
star_coord[3] = 127;
star_coord[4] = 122;
star_coord[5] = 50;
star_coord[6] = 10;
star_coord[7] = 49;
star_coord[8] = 109;
star_coord[9] = 127;
//reference shape to detect initial size
var s:Shape = shapeInRect(star_commands, star_coord);
var bounds:Rectangle = s.getBounds(s);
s.graphics.lineStyle(1);
s.graphics.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);
addChild(s);
//fit to target
var targetSize:Rectangle = new Rectangle(150, 100, 75, 60);
//detect lesser factor - assuming you need to preserve proportions
var kx:Number = targetSize.width / (bounds.width);
var ky:Number = targetSize.height / (bounds.height);
var toUse:Number = kx < ky ? kx : ky;
//apply to coords
for (var i:int = 0; i < star_coord.length; i++) {
//size
star_coord[i] *= toUse;
//fix initial offset
star_coord[i] -= i % 2 == 0 ? bounds.x * toUse : bounds.y * toUse;
}
//draw
addChild(shapeInRect(star_commands, star_coord, targetSize));
}
private function shapeInRect(command:Vector.<int>, coord:Vector.<Number>, rect:Rectangle = null):Shape{
var s:Shape = new Shape();
addChild(s);
s.graphics.beginFill(0x003366);
s.graphics.drawPath(command, coord);
s.graphics.endFill();
if (rect){
s.graphics.lineStyle(1);
s.graphics.drawRect(0, 0, rect.width, rect.height);
s.x = rect.x;
s.y = rect.y;
}
return s;
}

ActionScript 3.0 AddChild Function Not Working

I have tested out my code and the addchild won't work. No errors are outputted.
package{
import flash.display.MovieClip;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.display.*;
import flash.events.*;
import flash.geom.Rectangle;
import flash.media.Sound;
import flash.text.*;
public class Game extends flash.display.MovieClip{
public static const STATE_INIT:int = 10;
public static const STATE_PLAY:int = 20;
public static const STATE_END_GAME:int = 30;
public var gameState:int = 0;
public var score:int = 0;
public var chances:int = 5;
public var bg:MovieClip;
public var enemies:Array;
public var player:MovieClip;
public var level:Number = 0;
public var scoreLabel:TextField = new TextField
public var levelLabel:TextField = new TextField
public var chancesLabel:TextField = new TextField
public var scoreText:TextField = new TextField
public var levelText:TextField = new TextField
public var chancesText:TextField = new TextField
public const SCOREBOARD_Y:Number = 380
public function Game(){
addEventListener(Event.ENTER_FRAME, gameLoop);
bg = new BackImage();
addChild(bg);
scoreLabel.text = "Score:";
levelLabel.text = "level:";
chancesLabel.text = "Misses:";
scoreText.text = "0";
levelText.text = "1";
chancesText.text = "5";
scoreLabel.y = SCOREBOARD_Y;
levelLabel.y = SCOREBOARD_Y;
chancesLabel.y = SCOREBOARD_Y;
scoreText.y = SCOREBOARD_Y;
levelText.y = SCOREBOARD_Y;
chancesText.y = SCOREBOARD_Y;
scoreLabel.x = 5;
scoreText.x = 50;
chancesLabel.x = 105;
chancesText.x = 155;
levelLabel.x = 205;
levelText.x = 260
addChild(scoreLabel);
addChild(levelLabel);
addChild(chancesLabel);
addChild(scoreText);
addChild(levelText);
addChild(chancesText);
gameState = STATE_INIT;
}
public function gameLoop(e:Event):void{
switch(gameState){
case STATE_INIT:
initGame();
break;
case STATE_PLAY:
playGame();
break;
case STATE_END_GAME:
endGame();
break;
}
}
public function initGame():void{
score = 0;
chances = 5;
player = new playerImage();
enemies = new Array();
level = 1;
levelText.text = level.toString();
addChild(player);
player.startDrag(true,new Rectangle(0,0,550,400))
gameState = STATE_PLAY
}
public function playGame():void{
player.rotation += 15;
makeEnemies();
moveEnemies();
testCollisions();
testForEnd();
}
public function makeEnemies():void{
var chance:Number = Math.floor(Math.random()*100);
var tempEnemy:MovieClip;
if (chance < 2 + level) {
tempEnemy = new EnemyImage()
tempEnemy.speed = 3 + level;
tempEnemy.gotoAndStop(Math.floor(Math.random()*5)+1);
tempEnemy.y = 435;
tempEnemy.x = Math.floor(Math.random()*515)
addChild(tempEnemy);
enemies.push(tempEnemy);
}
}
public function moveEnemies():void{
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
tempEnemy.y -= tempEnemy.speed;
if (tempEnemy.y < -35){
chances -= 1;
chancesText.text = chances.toString();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testCollisions():void {
var sound:Sound = new Pop();
var tempEnemy:MovieClip;
for (var i:int = enemies.length -1;i >= 0;i--){
tempEnemy = enemies[i];
if(tempEnemy.hitTestObject(player)){
score++;
scoreText.text = score.toString();
sound.play();
enemies.splice(i,1);
removeChild(tempEnemy);
}
}
}
public function testForEnd():void{
if(chances == 5){
gameState = STATE_END_GAME;
}
else if(score > level*20) {
level++;
levelText.text = level.toString();
}
}
public function endGame():void{
for(var i:int = 0; i< enemies.length; i++) {
removeChild(enemies[i]);
}
enemies = [];
player.stopDrag()
}
}
}
I have already tried adding this. and stage. in front of addchild and it still doesn't work.
This inside a file called Game.as
When you create your Game instance you need to add it as a child to the stage:
// I would probably rename the variable to 'game'
// 1st character of a variable name is conventionally lower-case
// var game:Game = new Game();
var Script:Game = new Game();
this.addChild(Script);

Gravity is not applied with Box2D for Flash (v2.1a)

I am trying to follow a couple of tutorials on Box2D, but somehow I can't seem to get the gravity to be applied. Below is my code (with the URLs that I read for tutorials), maybe there is something I overlooked? Thanks for your help!
package
{
import Box2D.Collision.Shapes.b2PolygonShape;
import Box2D.Common.Math.b2Vec2;
import Box2D.Dynamics.b2Body;
import Box2D.Dynamics.b2BodyDef;
import Box2D.Dynamics.b2DebugDraw;
import Box2D.Dynamics.b2FixtureDef;
import Box2D.Dynamics.b2World;
import org.osflash.signals.natives.NativeSignal;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
/*
* http://active.tutsplus.com/tutorials/games/introduction-to-box2d-for-flash-and-as3/
* http://blog.allanbishop.com/box2d-2-1a-tutorial-part-1/
* http://plasticsturgeon.com/2010/08/making-an-as3-game-in-box2d-flash-version-2-0-hello-world-box2d/
*/
[SWF(backgroundColor="#cccccc", frameRate="30", width="1280", height="720")]
public class Floor extends Sprite
{
private const WIDTH :uint = 1280;
private const HEIGHT :uint = 720;
private const FPS :uint = 30;
private const NUM_PIXELS_PER_METER :uint = 30;
private const TIMESTEP :Number = 0 / NUM_PIXELS_PER_METER;
private const VELOCITY_ITERATIONS :uint = 6;
private const POSITION_ITERATIONS :uint = 2;
private var _world :b2World;
private var _gravity :b2Vec2;
private var _updated :NativeSignal;
public function Floor()
{
init();
}
private function init():void
{
initStage();
initBox2D();
_updated = new NativeSignal ( this,
Event.ENTER_FRAME,
Event
);
_updated.add(onUpdated);
}
private function initStage():void
{
stage.frameRate = FPS;
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
}
private function initBox2D():void
{
_gravity = new b2Vec2(0, 10);
_world = new b2World(_gravity, true);
var vector:b2Vec2 = new b2Vec2();
// floor
vector.x = (WIDTH * 0.5) / NUM_PIXELS_PER_METER;
vector.y = (HEIGHT * 0.75) / NUM_PIXELS_PER_METER;
var floorBodyDef:b2BodyDef = new b2BodyDef();
floorBodyDef.position.Set(vector.x, vector.y);
var floorBody:b2Body = _world.CreateBody(floorBodyDef);
vector.x = (WIDTH * 0.5) / NUM_PIXELS_PER_METER;
vector.y = 32 / NUM_PIXELS_PER_METER;
var floorBox:b2PolygonShape = new b2PolygonShape();
floorBox.SetAsBox(vector.x, vector.y);
var floorFixture:b2FixtureDef = new b2FixtureDef();
floorFixture.shape = floorBox;
floorFixture.density = 1;
floorFixture.friction = 1;
floorBody.CreateFixture(floorFixture);
// box
vector.x = (WIDTH * 0.5) / NUM_PIXELS_PER_METER;
vector.y = (HEIGHT * 0.125) / NUM_PIXELS_PER_METER;
var boxBodyDef:b2BodyDef = new b2BodyDef();
boxBodyDef.type = b2Body.b2_dynamicBody;
boxBodyDef.position.Set(vector.x, vector.y);
var boxBody:b2Body = _world.CreateBody(boxBodyDef);
var box:b2PolygonShape = new b2PolygonShape();
box.SetAsBox(1, 1);
var boxFixtureDef:b2FixtureDef = new b2FixtureDef();
boxFixtureDef.shape = box;
boxFixtureDef.density = 1;
boxFixtureDef.friction = 0.3;
boxFixtureDef.restitution = 0.1;
boxBody.CreateFixture(boxFixtureDef);
// debug
var debug:Sprite = new Sprite();
addChild(debug);
var debugDraw:b2DebugDraw = new b2DebugDraw();
debugDraw.SetSprite(debug);
debugDraw.SetDrawScale(NUM_PIXELS_PER_METER);
debugDraw.SetLineThickness(1.0);
debugDraw.SetAlpha(1);
debugDraw.SetFillAlpha(0.4);
debugDraw.SetFlags(b2DebugDraw.e_shapeBit);
_world.SetDebugDraw(debugDraw);
}
private function onUpdated(_:Event):void
{
_world.Step ( TIMESTEP,
VELOCITY_ITERATIONS,
POSITION_ITERATIONS
);
_world.ClearForces();
_world.DrawDebugData();
}
}
}
Sorry for being an idiot, when copying the TIMESTEP constant from elsewhere, I got a result of 0... My bad.

How do I create a Swirl effect in AS3?

I want to manipulate and animate some BitmapData to create a swirl effect such as the one found in the link below:
http://www.flash-filter.net/swirl-effect.phtml
What techniques could I apply?
Btw: Yes, I do know the effect is ugly..
In case you're looking for how a swirl effect is achieved, i.e. the algorithm. Here is a nice step-by-step explanation of how the image is transformed: Image- Twist and Swirl Algorithm
There is a Pixel Bender filter for this. Check out this link:
http://www.adobe.com/cfusion/exchange/index.cfm?event=extensionDetail&extid=1536021
Here is a tutorial on Tweening Pixel Bender filters
http://plasticsturgeon.com/2011/03/pixel-transition-tweening-a-pixel-bender-filter-in-as3/
You may also want to check out the AS3 ImageProcessing library
http://blog.joa-ebert.com/imageprocessing-library/
This should give you a good starting point
Pixel Bender ist krieg!
While I do agree with the previous answers, I'd like to point out, that you can do this kind of effect by using only bitmap filters that are out there for years now: DisplacementMapFilter namely. Create a displacement map that moves pixels in a circular direction and apply this map to an image multiple times. This will get you a swirling transformation.
Here's my simple implementation.
The usage is pretty straightforward (see after the class).
package org.noregret.images
{
import flash.display.BitmapData;
import flash.display.BitmapDataChannel;
import flash.display.BlendMode;
import flash.display.DisplayObject;
import flash.display.GradientType;
import flash.display.InterpolationMethod;
import flash.display.SpreadMethod;
import flash.display.Sprite;
import flash.filters.DisplacementMapFilter;
import flash.filters.DisplacementMapFilterMode;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
/**
* #author Nox Noctis (http://noregret.org)
*/
public class Swirl
{
public var target : DisplayObject;
public var allowCache : Boolean = false;
public var levels : uint;
public var isDestroyed : Boolean;
protected var bitmapMargin : Point;
protected var filter : DisplacementMapFilter;
protected var radius : int;
protected var cache : Object;
protected var map : BitmapData;
protected var targetRect : Rectangle;
protected var mapOffset : Point;
protected var maxLevel : Number = 1;
public function Swirl(_target : DisplayObject, _filterLevels : uint = 10, _allowCache : Boolean = true)
{
target = _target;
allowCache = _allowCache;
levels = _filterLevels;
cache = {};
filter = new DisplacementMapFilter();
filter.componentX = BitmapDataChannel.RED;
filter.componentY = BitmapDataChannel.GREEN;
filter.scaleX = -20;
filter.scaleY = -20;
filter.mapPoint = new Point();
filter.mode = DisplacementMapFilterMode.IGNORE;
}
private function createDisplacementMap() : void
{
targetRect = target.getRect(target);
radius = Math.max(Math.max(targetRect.width, targetRect.height), 100) / 2;
radius = Math.sqrt(2) * radius;
mapOffset = new Point(radius - targetRect.width / 2, radius - targetRect.height / 2);
var mapSprite : Sprite = new Sprite();
var redLayer : Sprite = new Sprite();
var greenLayer : Sprite = new Sprite();
var grayLayer : Sprite = new Sprite();
mapSprite.addChild(redLayer);
mapSprite.addChild(greenLayer);
mapSprite.addChild(grayLayer);
var gradientMatrix : Matrix;
gradientMatrix = new Matrix();
gradientMatrix.createGradientBox(radius * 2, radius * 2, Math.PI / 2, -radius, -radius);
redLayer.graphics.lineStyle(0, 0, 0);
redLayer.graphics.beginGradientFill(GradientType.LINEAR, [0xFF0000, 0], [100, 100], [0, 255], gradientMatrix, SpreadMethod.PAD, InterpolationMethod.RGB);
redLayer.graphics.drawCircle(0, 0, radius);
redLayer.graphics.endFill();
greenLayer.graphics.lineStyle(0, 0, 0);
gradientMatrix.createGradientBox(radius * 2, radius * 2, 0, -radius, -radius);
greenLayer.graphics.beginGradientFill(GradientType.LINEAR, [0x00FF00, 0x00FF00], [0, 100], [10, 245], gradientMatrix, SpreadMethod.PAD, InterpolationMethod.RGB);
greenLayer.graphics.drawCircle(0, 0, radius);
greenLayer.graphics.endFill();
greenLayer.blendMode = BlendMode.ADD;
gradientMatrix = new Matrix();
gradientMatrix.createGradientBox(radius * 2, radius * 2, 0, -radius, -radius);
grayLayer.graphics.lineStyle(0, 0, 0);
grayLayer.graphics.beginGradientFill(GradientType.RADIAL, [0x808080, 0x808080], [0, 100], [0, 0xFF], gradientMatrix, SpreadMethod.PAD, InterpolationMethod.RGB);
grayLayer.graphics.drawCircle(0, 0, radius);
grayLayer.graphics.endFill();
var rect : Rectangle = mapSprite.getRect(mapSprite);
var matrix : Matrix = new Matrix();
matrix.translate(-rect.x, -rect.y);
if (map) {
map.dispose();
}
map = new BitmapData(rect.width, rect.height, false, 0xFF808080);
map.draw(mapSprite, matrix);
filter.mapBitmap = map;
}
public function swirlTo(ratio : Number) : BitmapData
{
if (isDestroyed) {
trace("Swirl: error! Tried to swirl on disposed item.");
return null;
}
if (ratio < 0) {
ratio = 0;
}
var level : uint = Math.round(levels * ratio);
var cacheName : String = getCacheName(level);
if (cache[cacheName]) {
return (cache[cacheName] as BitmapData).clone();
}
var rect : Rectangle = target.getRect(target);
if (!map || rect.width != targetRect.width || rect.height != targetRect.height) {
createDisplacementMap();
flushCache();
}
var point : Point = new Point(-targetRect.x, -targetRect.y);
bitmapMargin = new Point(point.x + mapOffset.x, point.y + mapOffset.y);
var bmp : BitmapData;
if (cache["l" + maxLevel]) {
bmp = cache["l" + maxLevel] as BitmapData;
} else {
bmp = new BitmapData(map.width, map.height, true, 0);
var matrix : Matrix = new Matrix();
matrix.translate(bitmapMargin.x, bitmapMargin.y);
bmp.draw(target, matrix, null, null, null, true);
}
if (level == 0) {
cache[cacheName] = bmp.clone();
return bmp;
}
var destPoint : Point = new Point();
for (var i : Number = maxLevel;i <= level; i++) {
bmp.applyFilter(bmp, bmp.rect, destPoint, filter);
if (allowCache) {
cache["l" + i] = bmp.clone();
}
}
maxLevel = Math.max(maxLevel, level);
return bmp;
}
private function getCacheName(level : uint) : String
{
return "l" + level;
}
public function flushCache() : void
{
for each (var bmp:BitmapData in cache) {
bmp.dispose();
}
cache = {};
}
public function destroy() : void
{
flushCache();
target = null;
map.dispose();
map = null;
isDestroyed = true;
}
}
}
Usage example:
package
{
import flash.display.Sprite;
import flash.display.Loader;
import flash.events.Event;
import flash.net.URLRequest;
import flash.system.LoaderContext;
import flash.display.Bitmap;
import org.noregret.images.Swirl;
[SWF(width="800",height="600",backgroundColor="#FFFFFF",fps="30")]
public class TestSwirl extends Sprite
{
private const loader:Loader = new Loader();
private const swirlBitmap:Bitmap = new Bitmap();
private var swirl:Swirl;
private var time:Number = 0;
public function TestSwirl()
{
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoadComplete);
var request:URLRequest = new URLRequest("http://i.stack.imgur.com/Vtsvm.gif");
loader.load(request, new LoaderContext(true));
}
protected function onLoadComplete(event:Event):void
{
var original:Bitmap = loader.content as Bitmap;
addChild(original);
swirlBitmap.bitmapData = original.bitmapData.clone();
swirlBitmap.x = original.x + original.width + 10;
addChild(swirlBitmap);
swirl = new Swirl(original,80);
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
protected function onEnterFrame(event:Event):void
{
var ratio:Number = Math.abs(Math.sin(time));
// ***
swirlBitmap.bitmapData = swirl.swirlTo(ratio);
// ***
time += .02;
}
}
}
I would suggest using Pixel Bender to create your own bitmap filters.

doubt regarding carrying data in custom events using actionscript

I am working on actionscript to generate a SWF dynamically using JSON data coming from an HTTP request. I receive the data on creationComplete and try to generate a tree like structure. I don’t create the whole tree at the same time. I create 2 levels, level 1 and level 2. My goal is to attach custom events on the panels which represent tree nodes. When users click the panels, it dispatches custom events and try to generate the next level. So, it goes like this :
On creation complete -> get JSON-> create top tow levels -> click on level 2-> create the level 2 and level 3 -> click on level 3-> create level 3 and 4. …and so on and so on. I am attaching my code with this email. Please take a look at it and if you have any hints on how you would do this if you need to paint a tree having total level number = “n” where n = 0 to 100
Should I carry the data around in CustomPageClickEvent class.
[code]
import com.iwobanas.effects.*;
import flash.events.MouseEvent;
import flash.filters.BitmapFilterQuality;
import flash.filters.BitmapFilterType;
import flash.filters.GradientGlowFilter;
import mx.controls.Alert;
private var roundedMask:Sprite;
private var panel:NewPanel;
public var oldPanelIds:Array = new Array();
public var pages:Array = new Array();
public var delPages:Array = new Array();
public function DrawPlaybook(pos:Number,title:String,chld:Object):void {
panel = new NewPanel(chld);
panel.title = title;
panel.name=title;
panel.width = 100;
panel.height = 80;
panel.x=pos+5;
panel.y=40;
var gradientGlow:GradientGlowFilter = new GradientGlowFilter();
gradientGlow.distance = 0;
gradientGlow.angle = 45;
gradientGlow.colors = [0xFFFFF0, 0xFFFFFF];
gradientGlow.alphas = [0, 1];
gradientGlow.ratios = [0, 255];
gradientGlow.blurX = 10;
gradientGlow.blurY = 10;
gradientGlow.strength = 2;
gradientGlow.quality = BitmapFilterQuality.HIGH;
gradientGlow.type = BitmapFilterType.OUTER;
panel.filters =[gradientGlow];
this.rawChildren.addChild(panel);
pages.push(panel);
panel.addEventListener(MouseEvent.CLICK,
function(e:MouseEvent){onClickHandler(e,title,chld)});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED,
function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
}
public function onClickHandler(e:MouseEvent,title:String,chld:Object):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPanelClicked(e:CustomPageClickEvent,title:String):void {
Alert.show("onCustomPanelClicked" + title);
var panel:NewPanel;
for each(var stp:NewPanel in pages){
startAnimation(e,stp);
}
if(title == e.panelClicked.title){
panel = new NewPanel(null);
panel.title = title;
panel.name=title;
panel.width = 150;
panel.height = 80;
panel.x=100;
panel.y=40;
this.rawChildren.addChild(panel);
var slideRight:SlideRight = new SlideRight();
slideRight.target=panel;
slideRight.duration=750;
slideRight.showTarget=true;
slideRight.play();
var jsonData = this.map.getValue(title);
var posX:Number = 50;
var posY:Number = 175;
for each ( var pnl:NewPanel in pages){
pages.pop();
}
for each ( var stp1:Object in jsonData.children){
panel = new NewPanel(null);
panel.title = stp1.text;
panel.name=stp1.id;
panel.width = 100;
panel.id=stp1.id;
panel.height = 80;
panel.x = posX;
panel.y=posY;
posX+=150;
var s:String="hi" + stp1.text;
panel.addEventListener(MouseEvent.CLICK,
function(e:MouseEvent){onChildClick(e,s);});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED,
function(e:CustomPageClickEvent){onCustomPnlClicked(e)});
this.rawChildren.addChild(panel);
pages.push(panel);
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED,
function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
var slide:SlideUp = new SlideUp();
slide.target=panel;
slide.duration=1500;
slide.showTarget=false;
slide.play();
}
}
}
public function onChildClick(e:MouseEvent,s:String):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==e.currentTarget.title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPnlClicked(e:CustomPageClickEvent):void {
for each ( var pnl:NewPanel in pages){
pages.pop();
}
}
private function fadePanel(event:Event,panel:NewPanel):void{
panel.alpha -= .005;
if (panel.alpha <= 0){
panel.removeEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel);});
};
panel.title="";
}
private function startAnimation(event:CustomPageClickEvent,panel:NewPanel):void{
panel.addEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel)});
}
[/code]
Thanks in advance.
Palash
completely forgot i don't have enough rep to edit...
import com.iwobanas.effects.*;
import flash.events.MouseEvent;
import flash.filters.BitmapFilterQuality;
import flash.filters.BitmapFilterType;
import flash.filters.GradientGlowFilter;
import mx.controls.Alert;
private var roundedMask:Sprite;
private var panel:NewPanel;
public var oldPanelIds:Array = new Array();
public var pages:Array = new Array();
public var delPages:Array = new Array();
public function DrawPlaybook(pos:Number,title:String,chld:Object):void {
panel = new NewPanel(chld);
panel.title = title;
panel.name=title;
panel.width = 100;
panel.height = 80;
panel.x=pos+5;
panel.y=40;
var gradientGlow:GradientGlowFilter = new GradientGlowFilter();
gradientGlow.distance = 0;
gradientGlow.angle = 45;
gradientGlow.colors = [0xFFFFF0, 0xFFFFFF];
gradientGlow.alphas = [0, 1];
gradientGlow.ratios = [0, 255];
gradientGlow.blurX = 10;
gradientGlow.blurY = 10;
gradientGlow.strength = 2;
gradientGlow.quality = BitmapFilterQuality.HIGH;
gradientGlow.type = BitmapFilterType.OUTER;
panel.filters = [gradientGlow];
this.rawChildren.addChild(panel);
pages.push(panel);
panel.addEventListener(MouseEvent.CLICK, function(e:MouseEvent){onClickHandler(e,title,chld)});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED, function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
}
public function onClickHandler(e:MouseEvent,title:String,chld:Object):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPanelClicked(e:CustomPageClickEvent,title:String):void {
Alert.show("onCustomPanelClicked" + title);
var panel:NewPanel;
for each(var stp:NewPanel in pages){
startAnimation(e,stp);
}
if(title == e.panelClicked.title){
panel = new NewPanel(null);
panel.title = title;
panel.name=title;
panel.width = 150;
panel.height = 80;
panel.x=100;
panel.y=40;
this.rawChildren.addChild(panel);
var slideRight:SlideRight = new SlideRight();
slideRight.target=panel;
slideRight.duration=750;
slideRight.showTarget=true;
slideRight.play();
var jsonData = this.map.getValue(title);
var posX:Number = 50;
var posY:Number = 175;
for each ( var pnl:NewPanel in pages){
pages.pop();
}
for each ( var stp1:Object in jsonData.children){
panel = new NewPanel(null);
panel.title = stp1.text;
panel.name=stp1.id;
panel.width = 100;
panel.id=stp1.id;
panel.height = 80;
panel.x = posX;
panel.y=posY;
posX += 150;
var s:String="hi" + stp1.text;
panel.addEventListener(MouseEvent.CLICK, function(e:MouseEvent){onChildClick(e,s);});
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED, function(e:CustomPageClickEvent){onCustomPnlClicked(e)});
this.rawChildren.addChild(panel);
pages.push(panel);
this.addEventListener(CustomPageClickEvent.PANEL_CLICKED, function(e:CustomPageClickEvent){onCustomPanelClicked(e,title)});
var slide:SlideUp = new SlideUp();
slide.target=panel;
slide.duration=1500;
slide.showTarget=false;
slide.play();
}
}
}
public function onChildClick(e:MouseEvent,s:String):void {
for each(var stp1:NewPanel in pages){
if(stp1.title==e.currentTarget.title){
var eventObj:CustomPageClickEvent = new CustomPageClickEvent("panelClicked");
eventObj.panelClicked = stp1;
dispatchEvent(eventObj);
}
}
}
private function onCustomPnlClicked(e:CustomPageClickEvent):void {
for each ( var pnl:NewPanel in pages){
pages.pop();
}
}
private function fadePanel(event:Event,panel:NewPanel):void{
panel.alpha -= .005;
if (panel.alpha <= 0){
panel.removeEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel);});
};
panel.title="";
}
private function startAnimation(event:CustomPageClickEvent,panel:NewPanel):void{
panel.addEventListener(Event.ENTER_FRAME,
function(e:Event){fadePanel(e,panel)});
}