0
我正在嘗試做一些非常簡單的動畫:使一組精靈動畫,以便無論他們在舞臺上的哪個位置,他們都朝着單點(在這種情況下,舞臺)。向點動畫精靈
它只適用於其中的一些。他們中有些人就坐在那裏。我無法弄清楚爲什麼。我認爲它與atan2以及我使用它的方式有關,但我不確定是什麼。有人能看到嗎?
感謝,
大衛
package
{
import Ball;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
public class MoveBalls extends Sprite {
private var balls:Array = new Array();
private var speed:Number = new Number(10);
public function MoveBalls() {
init();
}
private function init():void {
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
for(var i:int = 0; i<30; i++)
{
var ball:Ball = new Ball(20);
ball.x = getRandomNumber();
if(ball.x > stage.stageWidth) ball.x = stage.stageWidth -10;
if(ball.x < 0) ball.x = 10;
trace(ball.x);
ball.y = getRandomNumber();
if(ball.y >stage.stageHeight) ball.y = stage.stageHeight - 10;
if(ball.y < 0) ball.y = 10;
addChild(ball);
balls.push(ball);
}
addEventListener(Event.ENTER_FRAME, onEnterFrame);
}
private function getRandomNumber():Number {
var decider:Number = Math.random();
if (decider < 0.5) {
return Math.random()*1000;
} else {
return Math.random()*-1000;
}
}
public function onEnterFrame(event:Event):void {
var targetX:Number = stage.stageWidth/2;
var targetY:Number = stage.stageHeight/2;
for(var i:int=0; i < balls.length; i++)
{
var startX:Number = balls[i].x;
var startY:Number = balls[i].y;
var atanX:Number = (targetX - startX);
var atanY:Number = (targetY - startY);
if(atanX > .1) //just stop when it's close enough to the center
{
var ang:Number = Math.atan2(atanY, atanX);
var xSpeed:Number = Math.cos(ang)*speed;
var ySpeed:Number = Math.sin(ang)*speed;
balls[i].x += xSpeed;
balls[i].y += ySpeed;
}
}
}
}
}
//ball class
package {
import flash.display.Sprite;
public class Ball extends Sprite {
private var radius:Number;
private var color:uint;
public function Ball(radius:Number=40, color:uint=0xff0000) {
this.radius = radius;
this.color = color;
init();
}
public function init():void {
graphics.beginFill(color);
graphics.drawCircle(0, 0, radius);
graphics.endFill();
}
}
}
是(衛生署!)好點。但即使我做出這樣的改變,有時候有些球會坐在那裏。 – David 2010-11-06 00:52:22
更新:問題似乎與該條件有關,無論是在其原始狀態還是作爲修改:if(atanX> .1 || atanY> .1)。一旦我刪除條件,球不再掛。不過,我不知道爲什麼。 – David 2010-11-06 13:13:42
現在它應該可以工作。 – 2010-11-06 18:21:55