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

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.

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;
}

Moving b2body With Keyboard

I have this code that gives the b2Body an impulse towards the cursor when you click on stage.
private function clicked(e:MouseEvent):void
{
var impulse_x:Number = (mouseX / world_scale - mainChar.GetPosition().x);
var impulse_y:Number = (mouseY / world_scale - mainChar.GetPosition().y);
var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}
I was trying to use keyboard right arrow key for movement and so in the update function I added the if key[Keyboard.RIGHT]:
private function update(e:Event):void {
world.Step (1 / 30, 10, 10);
if (key[Keyboard.RIGHT]) {
impulse_x = 3;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}
}
private function onKeyUp(e:KeyboardEvent):void
{
key[e.keyCode] = false;
}
private function onKeyDown(e:KeyboardEvent):void
{
key[e.keyCode] = true;
}
But the b2body goes to top left on the screen and stays there and doesn't move. I am changing the impulse value that then goes into the vector that is applied to the body.
Although it doesn't give me any errors.
EDIT: The whole code!
package
{
import Box2D.Collision.Shapes.b2PolygonShape;
import Box2D.Common.Math.b2Vec2;
import Box2D.Dynamics.b2Body;
import Box2D.Dynamics.b2BodyDef;
import Box2D.Dynamics.b2FixtureDef;
import Box2D.Dynamics.b2World;
import Box2D.Dynamics.Contacts.b2ContactEdge;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
import flash.events.MouseEvent;
import flash.ui.Keyboard;
public class Main extends Sprite
{
public var world:b2World = new b2World(new b2Vec2(0, 0), true);
public var world_scale:Number = 30;
public var mainChar:b2Body;
private var ground:b2Body;
public var keys:Array = [];
public var beingPressed:Boolean;
public var impulse_x:Number;
public var impulse_y:Number;
public var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
public function Main():void
{
createMainCharacter(stage.stageWidth / 2, stage.stageHeight / 2, 50, 100);
var th:uint = 10;
addEventListener(Event.ENTER_FRAME, update);
//stage.addEventListener(MouseEvent.CLICK, clicked);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
}
/**private function clicked(e:MouseEvent):void
{
var impulse_x:Number = (mouseX / world_scale - mainChar.GetPosition().x);
var impulse_y:Number = (mouseY / world_scale - mainChar.GetPosition().y);
var impulse:b2Vec2 = new b2Vec2(impulse_x, impulse_y);
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
}**/
private function update(e:Event):void
{
world.Step (1 / 30, 10, 10);
var temp:Sprite;
for (var body:b2Body = world.GetBodyList(); body != null; body = body.GetNext())
{
if (body.GetUserData())
{
temp = body.GetUserData() as Sprite;
temp.x = body.GetPosition().x * world_scale;
temp.y = body.GetPosition().y * world_scale;
temp.rotation = body.GetAngle() * (180 / Math.PI); // radians to degrees
}
}
if (keys[Keyboard.RIGHT])
{
impulse_x = 3;
impulse_y = 0;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());
} else {
impulse_x = 0;
impulse_y = 0;
}
}
private function createMainCharacter(x:Number, y:Number, width:Number, height:Number):void
{
var mainCharSprite:Sprite = new Sprite();
mainCharSprite.graphics.beginFill(0x000000);
mainCharSprite.graphics.drawRect( -width / 2, -height / 2 , width, height);
mainCharSprite.graphics.endFill;
mainCharSprite.x = x;
mainCharSprite.y = y;
addChild(mainCharSprite);
var mainCharDef:b2BodyDef = new b2BodyDef();
mainCharDef.userData = mainCharSprite;
mainCharDef.type = b2Body.b2_dynamicBody;
mainCharDef.position.Set (x / world_scale, y / world_scale);
mainChar = world.CreateBody(mainCharDef);
var shape:b2PolygonShape = new b2PolygonShape();
shape.SetAsBox((width / 2) / world_scale, (height / 2) / world_scale);
var fixtureDef:b2FixtureDef = new b2FixtureDef();
fixtureDef.shape = shape;
fixtureDef.restitution = 0.1;
fixtureDef.friction = 0.1;
fixtureDef.density = 0.5;
mainChar.CreateFixture(fixtureDef);
}
private function onKeyUp(e:KeyboardEvent):void
{
keys[e.keyCode] = false;
}
private function onKeyDown(e:KeyboardEvent):void
{
keys[e.keyCode] = true;
}
}
}
Changing the values of impulse_x and impulse_y is not going to update the values used by the b2Vec2 impulse. In AS3 primitives are passed by value not by reference. If you want the b2Vec2 object referenced by the variable impulse to change its values you need to change them directly on the object itself:
impulse.x = 3.0;
impulse.y = 0.0;
mainChar.ApplyImpulse(impulse, mainChar.GetPosition());

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.

ActionScript - Ignoring Passed Arguments?

i've been studying this code example for Rung-Kutta physics but i don't understand what is happening with the acceleration(p:Point, v:Point):Point function. the function accepts 2 point objects as required arguments but doesn't use them in the function while simply returning a new point.
i'm unfamiliar with this style of argument passing. can someone explain the significance of this function to me?
the source is from Keith Peters' book Advanced ActionScript 3.0 Animation, Chapter 6 - Advanced Physics, page 246.
package {
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.geom.Point;
import flash.utils.getTimer;
public class RK2 extends Sprite
{
private var _ball:Sprite;
private var _position:Point;
private var _velocity:Point;
private var _gravity:Number = 32;
private var _bounce:Number = -0.6;
private var _oldTime:int;
private var _pixelsPerFoot:Number = 10;
public function RK2()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
_ball = new Sprite();
_ball.graphics.beginFill(0xff0000);
_ball.graphics.drawCircle(0, 0, 20);
_ball.graphics.endFill();
_ball.x = 50;
_ball.y = 50;
addChild(_ball);
_velocity = new Point(10, 0);
_position = new Point(_ball.x / _pixelsPerFoot, _ball.y / _pixelsPerFoot);
_oldTime = getTimer();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function onEnterFrame(event:Event):void
{
var time:int = getTimer();
var elapsed:Number = (time - _oldTime) / 1000;
_oldTime = time;
var accel1:Point = acceleration(_position, _velocity);
var position2:Point = new Point();
position2.x = _position.x + _velocity.x * elapsed;
position2.y = _position.y + _velocity.y * elapsed;
var velocity2:Point = new Point();
velocity2.x = _velocity.x + accel1.x * elapsed;
velocity2.y = _velocity.y + accel1.x * elapsed;
var accel2:Point = acceleration(position2, velocity2);
_position.x += (_velocity.x + velocity2.x) / 2 * elapsed;
_position.y += (_velocity.y + velocity2.y) / 2 * elapsed;
_velocity.x += (accel1.x + accel2.x) / 2 * elapsed;
_velocity.y += (accel1.y + accel2.y) / 2 * elapsed;
if(_position.y > (stage.stageHeight - 20) / _pixelsPerFoot)
{
_position.y = (stage.stageHeight - 20) / _pixelsPerFoot;
_velocity.y *= _bounce;
}
if(_position.x > (stage.stageWidth - 20) / _pixelsPerFoot)
{
_position.x = (stage.stageWidth - 20) / _pixelsPerFoot;
_velocity.x *= _bounce
}
else if(_position.x < 20 / _pixelsPerFoot)
{
_position.x = 20 / _pixelsPerFoot;
_velocity.x *= _bounce;
}
_ball.x = _position.x * _pixelsPerFoot;
_ball.y = _position.y * _pixelsPerFoot;
}
private function acceleration(p:Point, v:Point):Point
{
return new Point(0, _gravity);
}
}
}
I think the author may be using the method acceleration as a place holder, perhaps for updates on a subsequent chapter.
Of course as it is right now, the acceleration method could be rewritten as
private function acceleration(...rest):Point {
return new Point(0, _gravity);
}
Or the arguments could be removed completely (though that would require the places where the method is called to be updated to not contain any arguments.)
This isn't a style of programming per se, but, I have seen this type of placeholder code put into books before.
You also could set the arguments with a null as default, so they are optional.
private function acceleration(p:Point = null, v:Point = null):Point
{
return new Point(0, _gravity);
}

SimpleButton Not Displaying

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.