Animated Pie Chart in AS3 - actionscript-3

i'm trying to make an animated pie chart in AS3, which it only shows a single var, but this var updates every X seconds. What I wanna do, it's to animated this pie chart to update to the new "status" with a tween animation. Something I can't make work. I already tried with tweenmax and such.
This is my pie chart code generator:
var degree: Number = 90;
var degChange: Number = 1;
var circleR: Number = 100;
var circleX: Number = 100;
var circleY: Number = 100;
var angleR: Number = circleR / 4;
var spBoard: Sprite = new Sprite();
spBoard.x = circleX;
spBoard.y = circleY;
C1.Maskmc.addChild(spBoard);
var shFill: Shape = new Shape();
shFill.graphics.lineStyle(1, 0x000000);
shFill.graphics.moveTo(0, 0);
shFill.graphics.lineTo(circleR, 0);
shFill.x = 0;
shFill.y = 0;
var shAngle: Shape = new Shape();
spBoard.addChild(shFill);
function updatePicture(t: Number): void {
var radianAngle: Number //=// t * Math.PI / 180.0;
var i: int;
shFill.graphics.clear();
shFill.graphics.moveTo(0, 0);
shFill.graphics.beginFill(0xFF00FF, 1);
for (i = 0; i <= t; i++) {
shFill.graphics.lineTo(circleR * Math.cos(i * Math.PI / 180), -circleR * Math.sin(i * Math.PI / 180));
trace(i)
}
shFill.graphics.lineTo(0, 0);
shFill.graphics.endFill();
}
var clockTimerTRas: Timer = new Timer(1000, 0);
clockTimerTRas.addEventListener(TimerEvent.TIMER, UpdateP);
clockTimerTRas.start();
function UpdateP(evt: Event): void {
var TurnoEstaHora
var TurnoActual_A: int = (it takes a var from a php here)
degree = TurnoActual_A * (11.305)
updatePicture(degree);
}
Which as i said before, it only makes a circle or incomplete circle depending on the var that loads from the PHP.
So far it works something like this, https://media.giphy.com/media/qiutE2wCo1YXe/giphy.gif
I wanna tween that animation. Any ideas?
Thank you!

Here an example:
import flash.display.Sprite;
import fl.transitions.Tween;
import fl.transitions.easing.*;
var tempSprite:Sprite = new Sprite();
addChild(tempSprite);
tempSprite.x = 100;
tempSprite.y = 100;
function convertAngleToRadians(angle:Number):Number
{
return angle / 180 * Math.PI;
}
function fillRound(
graphics:Graphics,
color:uint = 0x000000,
alpha:Number = 1,
radius:Number = 10,
startAngle:Number = 0,
endAngle:Number = 360,
angleStep:Number = 1):void
{
var tempRadians:Number;
var startRadians:Number = convertAngleToRadians(startAngle);
var endRadians:Number = convertAngleToRadians(endAngle);
var radiansStep:Number = convertAngleToRadians(angleStep);
var tempPoint:Point;
graphics.beginFill(color, alpha);
if (endAngle % 360 == startAngle % 360)
{
graphics.drawCircle(0, 0, radius);
}else
{
var pointsCount:Number = Math.ceil((endAngle - startAngle) / angleStep);
for (var pointIndex:int = 0; pointIndex <= pointsCount; pointIndex++)
{
tempRadians = startRadians + pointIndex * radiansStep;
tempPoint = new Point();
tempPoint.x = Math.cos(tempRadians) * radius;
tempPoint.y = Math.sin(tempRadians) * radius;
graphics.lineTo(tempPoint.x, tempPoint.y);
}
}
graphics.endFill();
}
var _curPieStep:Number = 0;
function get curPieStep():Number
{
return _curPieStep;
}
function set curPieStep(value:Number):void
{
_curPieStep = value;
drawPie();
}
var pieMaxStep:int = 30;
var pieAngleStep:int = 360 / pieMaxStep;
function drawPie():void
{
tempSprite.graphics.clear();
fillRound(tempSprite.graphics, 0xFF0000, 1, 100, 0, pieAngleStep * curPieStep);
}
var myTween:Tween = new Tween(this, "curPieStep", Bounce.easeOut, 0, pieMaxStep, 4, true);
You may just copy'n'paste it into Flash IDE and check the result.

Try this
import flash.utils.Timer;
import flash.events.TimerEvent;
var degree: Number = 90;
var degChange: Number = 1;
var circleR: Number = 100;
var circleX: Number = 100;
var circleY: Number = 100;
var angleR: Number = circleR / 4;
var spBoard: Sprite = new Sprite();
spBoard.x = circleX;
spBoard.y = circleY;
C1.Maskmc.addChild(spBoard);
var shFill: Shape = new Shape();
shFill.graphics.lineStyle(1, 0x000000);
shFill.graphics.moveTo(0, 0);
shFill.graphics.lineTo(circleR, 0);
shFill.x = 0;
shFill.y = 0;
shFill.graphics.clear();
shFill.graphics.moveTo(0, 0);
shFill.graphics.beginFill(0xFF00FF, 1);
var shAngle: Shape = new Shape();
spBoard.addChild(shFill);
function updatePicture(t: Number): void {
var radianAngle: Number //=// t * Math.PI / 180.0;
var i: int;
i = clockTimerTRas.currentCount ;
shFill.graphics.lineTo(circleR * Math.cos(i * Math.PI / 180), -circleR * Math.sin(i * Math.PI / 180));
trace(i)
}
var TurnoActual_A: int = (100) ;
var clockTimerTRas: Timer = new Timer(10, TurnoActual_A);
clockTimerTRas.addEventListener(TimerEvent.TIMER, UpdateP);
clockTimerTRas.start();
function UpdateP(evt: Event): void {
var TurnoEstaHora
degree = TurnoActual_A * (11.305)
updatePicture(degree);
}

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

HTML5 Canvas game, timer

Problem
Hello, I am creating a game and am stuck on how to get a timer on the canvas. I am aware that there are plenty of questions on Stackoverflow already about this topic.
Question
Could someone please tell me why my code does not work.
Code
var game = create_game();
game.init();
function create_game() {
debugger;
var level = 1;
var projectiles_per_level = 1;
var min_speed_per_level = 1;
var max_speed_per_level = 2;
var last_projectile_time = 0;
var next_projectile_time = 0;
var width = 600;
var height = 500;
var delay = 1000;
var item_width = 30;
var item_height = 30;
var total_projectiles = 0;
var projectile_img = new Image();
var projectile_w = 30;
var projectile_h = 30;
var player_img = new Image();
var background_img = new Image();
var c, ctx;
var projectiles = [];
var player = {
x: 200,
y: 400,
score: 0
};
function init() {
background_img.src = "background.png";
projectile_img.src = "projectile.png";
player_img.src = "player.png";
level = 1;
total_projectiles = 0;
projectiles = [];
c = document.getElementById("c");
ctx = c.getContext("2d");
ctx.fillStyle = "#410b11";
ctx.fillRect(0, 0, 500, 600);
c.addEventListener("mousemove", function (e) {
//moving over the canvas.
var bounding_box = c.getBoundingClientRect();
player.x = (e.clientX - bounding_box.left) * (c.width / bounding_box.width) - player_img.width / 2;
}, false);
setupProjectiles();
requestAnimationFrame(tick);
}
function tick() {
Most of game logic is here, I deleted as it I dont believe it helped keeping it in.
var i;
var projectile;
var dateNow = Date.now();
c.width = c.width;
ctx.drawImage(background_img, 0, 0);
for (i = 0; i < projectiles.length; i++) {
projectile = projectiles[i];
if (dateNow > projectile.delay) {
projectile.y += projectile.v;
if (collision(projectile)) {
initProjectile(i);
player.score++;
} else if (projectile.y > height) {
initProjectile(i);
} else {
ctx.drawImage(projectile_img, projectile.x, projectile.y);
}
}
}
ctx.font = "bold 24px sans-serif";
ctx.fillStyle = "#d1c09c";
ctx.fillText(player.score, c.width - 50, 50);
ctx.fillText("Level: " + level, 20, 50);
ctx.drawImage(player_img, player.x, player.y);
maybeIncreaseDifficulty();
requestAnimationFrame(tick);
This is where i was going to put my code for the timer:
var startTime;
function drawElapsedTime(){
var elapsed=parseInt((new Date() - startTime)/1000);
ctx.beginPath();
ctx.fillStyle="red";
ctx.font="bold 24px sans-serif";
g.fillText(elapsed+" secs", 75,25);
g.restore();
}
}
return {
init: init
};
}
I hope this makes sense, sorry for the overload of code.
From what I see, you might have forgotten to initialize your startTime variable.
ParseInt() of something undefined returns NaN.
Make sure to assign a value to it and that this value is accessible in the scope of your drawElapsedTime() function.

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 to draw a series of arc segments across line segments

I'm trying to draw a 'countdown' circle that will produce a visual clock, but don't like the resulting shape as it is not smooth. The code below draws and fills a series of triangles that approximate a circle when the variable 'numberOfSides' is sufficiently large, but this is both inefficient and produces an ugly 'circle.' What I would like to do is draw a series of arcs across the line segments but I don't know how to do it. Can anyone give me a prod in the right direction?
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" minWidth="955" minHeight="600" frameRate="100" creationComplete="init()">
<mx:Script>
<![CDATA[
private var numberOfSides:int = 10;
private var angle:Number = 0;
private var lineLength:int = 100;
private var xStartingPos:int = 300;
private var yStartingPos:int = 300;
private var i:int = 90;//Start the drawing at 0 to 360;
private var speed:int = 100;
private var timer:Timer
private function init():void{
//uic.graphics.lineStyle(1);
uic.graphics.moveTo(xStartingPos,yStartingPos);
uic.graphics.beginFill(0xffff00);
timer = new Timer(speed, numberOfSides + 1);
timer.addEventListener(TimerEvent.TIMER,cont);
timer.start()
}
private function cont(event:TimerEvent):void{
angle = (Math.PI / numberOfSides * 2) * i;
var xAngle:Number = Math.sin(angle);
var yAngle:Number = Math.cos(angle);
var xResult:int = xAngle * lineLength;
var yResult:int = yAngle * lineLength;
uic.graphics.lineTo(xStartingPos + xResult, yStartingPos + (yResult*-1));
i++
}
]]>
</mx:Script>
<mx:Canvas id="uic"/>
</mx:Application>
This could be accomplished by drawing wedges using nl.funkymonkey.drawing.DrawingShapes:
Draw Wedge function:
public static function drawWedge(target:Graphics, x:Number, y:Number, radius:Number, arc:Number, startAngle:Number=0, yRadius:Number=0):void
{
if (yRadius == 0)
yRadius = radius;
target.moveTo(x, y);
var segAngle:Number, theta:Number, angle:Number, angleMid:Number, segs:Number, ax:Number, ay:Number, bx:Number, by:Number, cx:Number, cy:Number;
if (Math.abs(arc) > 360)
arc = 360;
segs = Math.ceil(Math.abs(arc) / 45);
segAngle = arc / segs;
theta = -(segAngle / 180) * Math.PI;
angle = -(startAngle / 180) * Math.PI;
if (segs > 0)
{
ax = x + Math.cos(startAngle / 180 * Math.PI) * radius;
ay = y + Math.sin(-startAngle / 180 * Math.PI) * yRadius;
target.lineTo(ax, ay);
for (var i:int = 0; i < segs; ++i)
{
angle += theta;
angleMid = angle - (theta / 2);
bx = x + Math.cos(angle) * radius;
by = y + Math.sin(angle) * yRadius;
cx = x + Math.cos(angleMid) * (radius / Math.cos(theta / 2));
cy = y + Math.sin(angleMid) * (yRadius / Math.cos(theta / 2));
target.curveTo(cx, cy, bx, by);
}
target.lineTo(x, y);
}
}
Example implementation, animating countdown timer:
var value:Number = 0;
addEventListener(Event.ENTER_FRAME, frameHandler);
function frameHandler(event:Event):void
{
var g:Graphics = graphics;
g.clear();
value += 0.01;
g.lineStyle(1, 0x0000ff, 0.25);
g.beginFill(0x123456, 0.25);
drawWedge(g, 100, 100, 50, (360 * value) % 360);
g.endFill();
}
Any graphics line style or fill may be used; or, the fill could be used as a mask.
An other piece of code I found online:
http://flassari.is/2009/11/pie-mask-in-as3/
Changed this into:
var circleToMask:Sprite = new Sprite();
circleToMask.graphics.beginFill(0x004BA5DC); // color circle 0x00RRGGBB
circleToMask.graphics.drawCircle(0, 0, 50);
circleToMask.graphics.endFill();
addChildAt(circleToMask, 0);
var circleMask:Sprite = new Sprite();
circleToMask.x = (circleMask.x = 50);
circleToMask.y = (circleMask.y = 50);
circleToMask.mask = circleMask;
addChild(circleMask);
// inner circle
var circleTopMask:Sprite = new Sprite();
circleTopMask.graphics.beginFill(0x00FFFFFF); // color inner circle
circleTopMask.graphics.drawCircle(0, 0, 25);
circleTopMask.graphics.endFill();
addChild(circleTopMask);
circleTopMask.x = 50;
circleTopMask.y = 50;
// textfield in the center
var myFormat:TextFormat = new TextFormat();
myFormat.size = 18;
var myText:TextField = new TextField();
myText.defaultTextFormat = myFormat;
myText.text = "0%";
myText.autoSize = TextFieldAutoSize.CENTER;
myText.y = 50 - (myText.height/2);
addChild(myText);
var percentage:Number = 0;
var tper:Number = 0;
addEventListener(Event.ENTER_FRAME, function (_arg1:Event):void{
graphics.clear();
// Percentage should be between 0 and 1
tper = percentage < 0 ? 0 : (percentage > 1 ? 1 : percentage);
// Draw the masked circle
circleMask.graphics.clear();
circleMask.graphics.beginFill(0);
drawPieMask(circleMask.graphics, tper, 50, 0, 0, (-(Math.PI) / 2), 3);
circleMask.graphics.endFill();
// Increase percentage with margins so it appears to stop for a short while
percentage = (percentage + 0.01);
if (percentage > 1){
percentage = 0;
}
myText.text = ((percentage*100).toFixed(0))+"%";
})
function drawPieMask(graphics:Graphics, percentage:Number, radius:Number = 50, x:Number = 0, y:Number = 0, rotation:Number = 0, sides:int = 6):void {
// graphics should have its beginFill function already called by now
graphics.moveTo(x, y);
if (sides < 3) sides = 3; // 3 sides minimum
// Increase the length of the radius to cover the whole target
radius /= Math.cos(1/sides * Math.PI);
// Shortcut function
var lineToRadians:Function = function(rads:Number):void {
graphics.lineTo(Math.cos(rads) * radius + x, Math.sin(rads) * radius + y);
};
// Find how many sides we have to draw
var sidesToDraw:int = Math.floor(percentage * sides);
for (var i:int = 0; i <= sidesToDraw; i++)
lineToRadians((i / sides) * (Math.PI * 2) + rotation);
// Draw the last fractioned side
if (percentage * sides != sidesToDraw)
lineToRadians(percentage * (Math.PI * 2) + rotation);
}
The size of the resuling FLA should be 100 x 100 px.
Resulting in:

The text around the center of the circle along the radius

Please help to solve the geometric issue. I'm creating multiple sectors of the wheel. Now I need to be placed in every sector the text oriented from the center of the circle to the edge. But somehow, everything goes awry.
Here is the class of one sector:
package comps
{
import flash.display.Shape;
import flash.display.Sprite;
import flash.filters.GlowFilter;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Vector3D;
import flash.net.URLRequest;
import flash.text.AntiAliasType;
import flash.text.Font;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
public class Sector extends Sprite
{
private var imageX1:Number;
private var imageY1:Number;
private var imageX2:Number;
private var imageY2:Number;
[Embed(source="font/SEGOEUIB.TTF", fontFamily="SegoeUI", mimeType="application/x-font", embedAsCFF="false", advancedAntiAliasing="true")]
private var MoolEmbed:Class;
public function Sector(tip:String, rot:Number, centerX:Number, centerY:Number, innerRadius:Number, outerRadius:Number, startAngle:Number, arcAngle:Number, val:Number, color:uint, alpha:Number, url:String, value:Number, steps:int=20)
{
Font.registerFont(MoolEmbed);
var myArc:Sprite = new Sprite();
myArc.graphics.lineStyle(2);
myArc.graphics.beginFill(color, alpha);
drawSolidArc (myArc,centerX, centerY, innerRadius, outerRadius, startAngle, arcAngle, url, steps);
myArc.graphics.endFill();
this.addChild(myArc);
var myFormat:TextFormat = new TextFormat();
myFormat.size = 20;
myFormat.align = TextFormatAlign.CENTER;
myFormat.font = 'SegoeUI';
myFormat.bold = true;
var myText:TextField = new TextField();
myText.defaultTextFormat = myFormat;
myText.setTextFormat(myFormat);
myText.embedFonts = true;
myText.antiAliasType = AntiAliasType.ADVANCED;
myText.text = url;
this.addChild(myText);
myText.wordWrap = true;
myText.width = outerRadius - innerRadius;
myText.height = 20;
var sectorsNum:Number = rot/360;
textRotation(myText, rot*(sectorsNum-value) - rot*0.5, centerX, centerY);
myText.x = imageX1 + 0 * (imageX2 - imageX1);
myText.y = imageY1 + 0 * (imageY2 - imageY1);
//trace (myText.x + " " + myText.y);
var myGlow:GlowFilter = new GlowFilter();
myGlow.color = 0xFFFFFF;
myGlow.blurX = 20;
myGlow.blurY = 20;
myGlow.strength = 2;
myText.filters = [myGlow];
}
}
private function textRotation (target:TextField, angle:Number, centerX:Number, centerY:Number):void{
var point:Point=new Point(centerX + target.width/2, centerY + target.height/2);
var m:Matrix=target.transform.matrix;
m.tx -= point.x;
m.ty -= point.y;
m.rotate (angle*(Math.PI/180));
m.tx += point.x;
m.ty += point.y;
target.transform.matrix=m;
}
private function drawSolidArc (drawObj:Object, centerX:Number,centerY:Number,innerRadius:Number,outerRadius:Number,startAngle:Number,arcAngle:Number,url:String,steps:int=20):void {
var twoPI:Number = 2 * Math.PI;
var angleStep:Number = arcAngle/steps;
var angle:Number, i:int, endAngle:Number;
var xx:Number = centerX + Math.cos(startAngle * twoPI) * innerRadius;
var yy:Number = centerY + Math.sin(startAngle * twoPI) * innerRadius;
var xxInit:Number=xx;
var yyInit:Number=yy;
drawObj.graphics.moveTo(xx,yy);
for(i=1; i<=steps; i++) {
angle = (startAngle + i * angleStep) * twoPI;
xx = centerX + Math.cos(angle) * innerRadius;
yy = centerY + Math.sin(angle) * innerRadius;
drawObj.graphics.lineTo(xx,yy);
if (i==steps*0.5-1){
imageX1 = xx;
imageY1 = yy;
}
}
endAngle = startAngle + arcAngle;
for(i=0;i<=steps;i++) {
angle = (endAngle - i * angleStep) * twoPI;
xx = centerX + Math.cos(angle) * outerRadius;
yy = centerY + Math.sin(angle) * outerRadius;
drawObj.graphics.lineTo(xx,yy);
if (i==steps*0.5){
imageX2 = xx;
imageY2 = yy;
}
}
drawObj.graphics.lineTo(xxInit,yyInit);
}
}
}
And that's creating all the wheel:
sectorsNum = tarotAC.length;
for (var i:int = 0; i < sectorsNum; i++){
var arcAngle:Number = - 1/sectorsNum;
var startAngle:Number = arcAngle*i;
var arc:Sector = new Sector(FlexGlobals.topLevelApplication.mode, 360/sectorsNum, 0, 0, stageW*0.1, stageW*0.5, startAngle, arcAngle, Number(sectorsNum - i), tarotAC.getItemAt(i).color, 1, tarotAC.getItemAt(i).datas, tarotAC.getItemAt(i).url);
con.addChild(arc);
}
By looking at it, I would say your TextFields need to be moved up by their height. TextFields are created from the top and the coordinates you give them would fit better with the baseline. Maybe you could put your TextField in a Sprite, set the TextField's y to -height and then manipulate the container instead of the text itself:
var container:Sprite = new Sprite();
container.addChild(myText);
this.addChild(container);
myText.y = -myText.height;
textRotation(container, rot*(sectorsNum-value) - rot*0.5, centerX, centerY);
//you should of course modify textRotation's first parameter type
container.x = imageX1 + 0 * (imageX2 - imageX1);
container.y = imageY1 + 0 * (imageY2 - imageY1);