The text around the center of the circle along the radius - actionscript-3

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

Related

State Machine Cant get to work

Learning to code so this might sound noobish...
Using Action Script
I am trying to make my Agents react to my segments so they run away.
So I need to connect part of my Main code to my Agent code
Here is my code :
Main.as
package
{
import agent.Agent;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.events.KeyboardEvent;
import flash.geom.Point;
import flash.display.Stage;
public class Main extends Sprite
{
private var score:Score;
private var count:int;
private var bleh: int = 0;
private var Agents:Vector.<Agent>;
private var segments:Array;
private var numSegments:uint = 20;
private var player:Point = new Point (200, 200)
private var friend:Agent = new Agent;
private var snakeHead:SnakeHead;
private var snakeTail:SnakeTail;
private var background: Sprite;
private var border: Bushes;
private var xVel: Number;
private var yVel: Number;
public function Main():void
{
xVel = 0;
yVel = 0;
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}
private function init(e:Event = null):void
{
snakeHead = new SnakeHead();
snakeTail = new SnakeTail();
score = new Score();
border = new Bushes;
score.x = 11;
score.y = 14;
addChild(score);
stage.addChild(border);
count = 0;
addChildAt(snakeHead,0);
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
segments = new Array();
for(var i:uint = 0; i < numSegments; i++)
{
var segment:Segment = new Segment (10, 20);
addChildAt(segment,0);
addChildAt(snakeTail,0);
segments.push(segment);
}
//updatePoint();
addEventListener(Event.ENTER_FRAME, onEnterFrame);
removeEventListener(Event.ADDED_TO_STAGE, init);
stage.scaleMode = StageScaleMode.NO_SCALE;
stage.align = StageAlign.TOP_LEFT;
// entry point
background = new LevelOne(); //creates the background
addChildAt(background,0);
Agents = new Vector.<Agent>();
addEventListener(Event.ENTER_FRAME, gameloop);
for (var x:int = 0; x < 3; x++)
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = 400;
a.y = 300;
a.name = "Name"+x;
trace (x);
}
stage.addEventListener(MouseEvent.CLICK, createAgent);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, keyUp);
}
private function createAgent(e:MouseEvent):void
{
var a:Agent = new Agent();
addChild(a);
Agents.push(a);
a.x = mouseX;
a.y = mouseY;
}
private function gameloop(evt:Event):void
{
for (var i:int = 0; i < Agents.length; i++)
{
Agents[i].update();
if (snakeHead.hitTestObject(Agents[i]))
{
//trace (Agents[i].name);
removeAgent(Agents[i]);
Agents.splice(i,1);
count ++;
score.lowercasetext.text = count.toString();
trace("count: " + count);
}
}
}
private function onEnterFrame(evt:Event):void
{
player.x += xVel;
player.y += yVel;
drag(snakeHead, player.x, player.y);
drag(segments[0], snakeHead.x, snakeHead.y);
for(var i:uint = 1; i < numSegments; i++)
{
var segmentA:Segment = segments[i];
var segmentB:Segment = segments[i - 1];
drag(segmentA, segmentB.x, segmentB.y);
var PlayerHalfWidth: Number = segments[i].width / 2;
var PlayerHalfHeight: Number = segments[i].height / 2;
if (segments[i].x + PlayerHalfWidth > stage.stageWidth) {
segments[i].x = stage.stageWidth - PlayerHalfWidth;
} else if (segments[i].x - PlayerHalfWidth < 0) {
segments[i].x = 0 + PlayerHalfWidth;
}
if (segments[i].y + PlayerHalfHeight > stage.stageHeight) {
segments[i].y = stage.stageHeight - PlayerHalfHeight;
}else if (segments[i].y - PlayerHalfHeight < 0) {
segments[i].y = 0 + PlayerHalfHeight;
}
var playerHalfWidth: Number = segments[i - 1].width / 2;
var playerHalfHeight: Number = segments[i - 1].height / 2;
if (segments[i - 1].x + playerHalfWidth > stage.stageWidth) {
segments[i - 1].x = stage.stageWidth - playerHalfWidth;
} else if (segments[i - 1].x - playerHalfWidth < 0) {
segments[i - 1].x = 0 + playerHalfWidth;
}
if (segments[i - 1].y + playerHalfHeight > stage.stageHeight) {
segments[i - 1].y = stage.stageHeight - playerHalfHeight;
}else if (segments[i - 1].y - playerHalfHeight < 0) {
segments[i - 1].y = 0 + playerHalfHeight;
}
}
drag(snakeTail, segments[19].x, segments[19].y);
var HeadHalfWidth: Number = snakeHead.width / 2;
var HeadHalfHeight: Number = snakeHead.height / 2;
if (snakeHead.x + HeadHalfWidth > stage.stageWidth) {
snakeHead.x = stage.stageWidth - HeadHalfWidth;
} else if (snakeHead.x - HeadHalfWidth < 0) {
snakeHead.x = 0 + HeadHalfWidth;
}
if (snakeHead.y + HeadHalfHeight > stage.stageHeight) {
snakeHead.y = stage.stageHeight - HeadHalfHeight;
}else if (snakeHead.y - HeadHalfHeight < 0) {
snakeHead.y = 0 + HeadHalfHeight;
}
//drag(segments[19], snakeTail.x, snakeTail.y);
/*for each (var a: Agent in Agents) {
a.update();
trace ("Follow me on Twitter.");
if(segments[0].hitTestObject(a))
{
trace("True");
trace(bleh + " " + "F*CKING HELL!");
trace(a.name);
stage.removeChild(Agents[1]);
}
}*/
}
private function removeAgent(a:Agent):void
{
a.parent.removeChild(a);
trace("Collision Detected!");
}
private function keyDown (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player;
yVel = -5;
}
if (evt.keyCode == 83)
{
player;
yVel = 5;
}
if (evt.keyCode == 68)
{
player;
xVel = 5;
}
if (evt.keyCode == 65)
{
player;
xVel = -5;
}
//trace (player.x + " " + player.y);
trace (xVel + " " + yVel);
}
private function keyUp (evt: KeyboardEvent): void {
//87=w 68=d 83=s 65=a
if (evt.keyCode == 87)
{
player;
yVel = 0;
}
else if (evt.keyCode == 83)
{
player;
yVel = 0;
}
else if (evt.keyCode == 68)
{
player;
xVel = 0;
}
else if (evt.keyCode == 65)
{
player;
xVel = 0;
}
}
private function drag(segment:MovieClip, xpos:Number, ypos:Number):void
{
var dx:Number = xpos - segment.x;
var dy:Number = ypos - segment.y;
var angle:Number = Math.atan2(dy, dx);
segment.rotation = angle * 180 / Math.PI;
var w:Number = segment.getPin().x - segment.x;
var h:Number = segment.getPin().y - segment.y;
segment.x = xpos - w;
segment.y = ypos - h;
}
}
}
Agent.as
package agent
{
import agent.states.ChaseState;
import agent.states.ConfusionState;
import agent.states.FleeState;
import agent.states.IAgentState;
import agent.states.IdleState;
import agent.states.WanderState;
import flash.display.Graphics;
import flash.display.Shape;
import flash.display.Sprite;
import flash.geom.Point;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.display.MovieClip;
import flash.events.*;
import Segment;
import Main;
public class Agent extends MovieClip
{
private var mouses:mouse;
public static const IDLE:IAgentState = new IdleState(); //Define possible states as static constants
public static const WANDER:IAgentState = new WanderState();
public static const CHASE:IAgentState = new ChaseState();
public static const FLEE:IAgentState = new FleeState();
public static const CONFUSED:IAgentState = new ConfusionState();
public var snake:Segment;
private const RAD_DEG:Number = 180 / Math.PI;
private var _previousState:IAgentState; //The previous executing state
private var _currentState:IAgentState; //The currently executing state
private var _pointer:Shape;
private var _tf:TextField;
public var velocity:Point = new Point();
public var speed:Number = 0;
public var fleeRadius:Number = 100; //If the mouse is "seen" within this radius, we want to flee
public var chaseRadius:Number = 50; //If the mouse is "seen" within this radius, we want to chase
public var numCycles:int = 0; //Number of updates that have executed for the current state. Timing utility.
public function Agent()
{
//Boring stuff here
_tf = new TextField();
_tf.defaultTextFormat = new TextFormat("_sans", 10);
_tf.autoSize = TextFieldAutoSize.LEFT;
_pointer = new Shape();
mouses = new mouse();
snake = new Segment(1, 1);
/*g.beginFill(0);
g.drawCircle(0, 0, 5);
g.endFill();
g.moveTo(0, -5);
g.beginFill(0);
g.lineTo(10, 0);
g.lineTo(0, 5);
g.endFill();*/
addChild(mouses);
addChild(_tf);
_currentState = IDLE; //Set the initial state
}
/**
* Outputs a line of text above the agent's head
* #param str
*/
public function say(str:String):void {
_tf.text = str;
_tf.y = -_tf.height - 2;
}
/**
* Trig utility methods
*/
public function get canSeeMouse():Boolean {
var dot:Number = snake.x * velocity.x + snake.y * velocity.y;
return dot > 0;
}
public function get distanceToMouse():Number {
var dx:Number = x - snake.x;
var dy:Number = y - snake.y;
return Math.sqrt(dx * dx + dy * dy);
}
public function randomDirection():void {
var a:Number = Math.random() * 6.28;
velocity.x = Math.cos(a);
velocity.y = Math.sin(a);
}
public function faceMouse(multiplier:Number = 1):void {
var dx:Number = snake.x - x;
var dy:Number = snake.y - y;
var rad:Number = Math.atan2(dy, dx);
velocity.x = multiplier*Math.cos(rad);
velocity.y = multiplier*Math.sin(rad);
}
/**
* Update the current state, then update the graphics
*/
public function update():void {
if (!_currentState) return; //If there's no behavior, we do nothing
numCycles++;
_currentState.update(this);
x += velocity.x*speed;
y += velocity.y*speed;
if (x + velocity.x > stage.stageWidth || x + velocity.x < 0) {
x = Math.max(0, Math.min(stage.stageWidth, x));
velocity.x *= -1;
}
if (y + velocity.y > stage.stageHeight || y + velocity.y < 0) {
y = Math.max(0, Math.min(stage.stageHeight, y));
velocity.y *= -1;
}
mouses.rotation = RAD_DEG * Math.atan2(velocity.y, velocity.x);
}
public function setState(newState:IAgentState):void {
if (_currentState == newState) return;
if (_currentState) {
_currentState.exit(this);
}
_previousState = _currentState;
_currentState = newState;
_currentState.enter(this);
numCycles = 0;
}
public function get previousState():IAgentState { return _previousState; }
public function get currentState():IAgentState { return _currentState; }
}
}

Animated Pie Chart in AS3

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

How to make a movieClip move independent of the stage if added on it?

In my flash-made game, if my character jump on top of an enemy movieclip it spawns 3 minions from another class by MovieClip(root).addChild(spawn1);. In my minions class I've put the code for them to fall and stop upon hitting the ground and also follow my character.
I have a VCam(virtual camera) movieClip to follow my character(who moves on the stage, not the stage around him) with this code build-in:
import flash.events.Event;
import flash.geom.Matrix;
import flash.geom.Rectangle;
import flash.geom.Point;
import flash.display.MovieClip;
//VCam
addEventListener(Event.ENTER_FRAME, handleEnterFrame);
function handleEnterFrame(event:Event):void {
if (parent) {
parent.scaleX = 1 / scaleX;
parent.scaleY = 1 / scaleY;
if (rotation == 0) {
parent.x = (width / 2 - x) / scaleX;
parent.y = (height / 2 - y) / scaleY;
parent.rotation = 0;
} else {
var bounds:Rectangle = getBounds(this);
var angle:Number = rotation * Math.PI / 180;
var midX:Number = -x / scaleX;
var midY:Number = -y / scaleY;
var rx:Number = -bounds.width / 2;
var ry:Number = -bounds.height / 2;
var cos:Number = Math.cos(angle);
var sin:Number = Math.sin(angle);
var rotatedX:Number = rx * cos - ry * sin;
var rotatedY:Number = ry * cos + rx * sin;
var cornerX:Number = midX - rotatedX;
var cornerY:Number = midY - rotatedY;
cos = Math.cos(-angle);
sin = Math.sin(-angle);
parent.x = cornerX * cos - cornerY * sin;
parent.y = cornerY * cos + cornerX * sin;
parent.rotation = -rotation;
}
}
}
addEventListener(Event.REMOVED, handleRemoved, false, 0, true);
function handleRemoved(event:Event):void
{
removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
removeEventListener(Event.REMOVED, handleRemoved);
}
When I jump with my character it seems that the minions follow the movement of my vcam and not behaving normally, jumping with the camera and falling throu'the ground when the character falls.
If I add a child normally from the main timeline by addChild(m_clip); it does not behave like that.
Is there an easy fix? Thanks!
This is the minions class code:
package {
import flash.display.*;
import flash.events.*;
public class EnemySpawned extends MovieClip {
protected var gravitysp: Number = 1;
protected var ySpeedsp: Number = 0;
protected var Speedsp: Number = 6.5;
var charMTL:MovieClip;
public function EnemySpawned()
{
this.addEventListener(Event.ENTER_FRAME, movement);
trace('exist');
}
function movement(event:Event):void
{
var MTL:MovieClip = MovieClip(root);
charMTL = MTL.char1;
ySpeedsp += gravitysp;
if(! MTL.ground_1.hitTestPoint(this.x, this.y, true))
{
this.y += ySpeedsp;
}
if(ySpeedsp > 40)
{
ySpeedsp = 40;
}
for(var j:int = 0; j<20; j++)
{
if(MTL.ground_1.hitTestPoint(this.x, this.y, true))
{
this.y--
ySpeedsp = 0;
}
}
var Distance:Number = charMTL.x - this.x;
if(Distance < -charMTL.width/2 - this.width/2)
{
this.x -= Speedsp;
}
if(Distance > charMTL.width/2 + this.width/2)
{
this.x += Speedsp;
}
}
}
}
There is no moving of ground_1 movieClip via code.

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.

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