請問各位大大
請問變數要怎跨function共用!?
stage.addEventListener(MouseEvent.CLICK, fire);
function fire(e:MouseEvent){
var theeX:int = mouseX - theArrow.x;
var theeY:int = (mouseY - theArrow.y) * -1;
var bullet:Bullet = new Bullet();
bullet.x = 144.45;
bullet.y = 175.95;
bullet.addEventListener(Event.ENTER_FRAME, on_move_bullet);
this.addChild(bullet);
}
我的問題就在於上面的theeX/theeY, 無法傳給下面的theeX/theeY
請問要怎宣告我才能上上面的值傳給下面!?
<pre class="c" name="code">
class Bullet
{
//用來儲存theeX、theeY的私有變數,你的theeX、theeY是用int,不過要精準一點的話,應該會有浮點數,所以用Number是比較適合的,不過如果還是想用int的話,下面兩個變數的型別就要改int,總之要一致就是了
private var _newPositionX:Number;
private var _newPositionY:Number;
function Bullet(newPosX:Number,newPosY:Number)
{
//將點擊取得的theeX、 theeY指定給變數
_newPositionX = newPosX,
_newPositionY = newPosY;
}
//寫一個method來執行指定x,y值的動作
public function letBulletFly():viod
{
this.x = _newPositionX;
this.y = _newPositionY;
}
/*
其他原本的程式碼
...
*/
}
這樣子在生成Bullet的時候,就可以把theeX、theeY指定給Bullet
<pre class="c" name="code"> var bullet:Bullet = new Bullet(theeX,theeY);
然後在EnterFrame的Event發生時,執行剛剛寫的新method
<pre class="c" name="code">
function on_move_bullet(e:Event):void{
bullet.letBulletFly();
}
這不是把 var 寫在函數區塊外面就好了嗎?
大概這樣?
var theeX:int;
var theeY:int;
stage.addEventListener(MouseEvent.CLICK, fire);
function fire(e:MouseEvent){
theeX = mouseX - theArrow.x;
theeY = (mouseY - theArrow.y) * -1;
var bullet:Bullet = new Bullet();
bullet.x = 144.45;
bullet.y = 175.95;
bullet.addEventListener(Event.ENTER_FRAME, on_move_bullet);
this.addChild(bullet);
}
function on_move_bullet(e:Event):void{
bullet.x = theeY;
bullet.y = theeX;
}