0

我是Actionscript3的初学者,正在做一个小游戏的功课,这是符合条件的最终效果:http: //neowudesign.com/Ex03_hw.html。在这个游戏中,蝴蝶会避免被用户的光标触及。虽然我已经完成了工作,但由于我没有多少编码经验,所以代码很尴尬。所以我想知道如何有效地改进我的代码。这是我的原始代码:

import flash.geom.Rectangle;
import flash.geom.Point;
var rx:Number = 15;
var ry:Number = 15;
var rwidth:Number = 285;
var rheight:Number = 185;
var rect1:Rectangle = new Rectangle(rx,ry,rwidth,rheight);
var velx = 5;
var vely = 5;




stage.addEventListener(MouseEvent.MOUSE_MOVE, avoidMe);

function avoidMe(mouseEvent:MouseEvent):void
{
trace("mouseX: "+ mouseX);
trace("mouseY: "+ mouseY);
var point_1:Point = new Point(mouseX,mouseY);
var point_2:Point = new Point(myButterfly.x,myButterfly.y);
var distanceBetween:Number = Point.distance(point_1,point_2);
trace(distanceBetween);// 10

if (distanceBetween < 20 && myButterfly.x >= 15 && myButterfly.x <= 285 && myButterfly.y >= 15 && myButterfly.y <= 185)
{
    if (mouseX < myButterfly.x)
    {
        myButterfly.x +=  velx;
        trace("x is moving left");
    }
    else
    {
        myButterfly.x -=  velx;
        trace("x is moving right");
    }


    if (mouseY < myButterfly.y)
    {
        myButterfly.y +=  vely;
        trace("x is moving down");
    }
    else
    {
        myButterfly.y -=  vely;
        trace("x is moving up");
    }
}

if (myButterfly.x > 285)
{
    myButterfly.x = myButterfly.x - 40;
    trace("hit the right");
}

if (myButterfly.x < 15)
{
    myButterfly.x = myButterfly.x + 40;
    trace("hit the left");
}



if (myButterfly.y > 185)
{
    myButterfly.y = myButterfly.y - 40;
    trace("hit the bottom");
}

if (myButterfly.y < 15)
{
    myButterfly.y = myButterfly.y + 40;
    trace("hit the top");
}

}

4

1 回答 1

0

如果你想压缩你的代码,你可以试试这个:

if (distanceBetween < 20 && myButterfly.x >= 15 && myButterfly.x <= 285 && myButterfly.y >= 15 && myButterfly.y <= 185)
{
    myButterfly.x += (mouseX < myButterfly.x) ? velx : velx * -1;

    myButterfly.y += (mouseY < myButterfly.y) ? vely : vely * -1;

    // (expression) ? if expression true : if expression false; 
}

if (myButterfly.x > 285)
{
    myButterfly.x -= 40;
    trace("hit the right");
}

if (myButterfly.x < 15)
{
    myButterfly.x += 40;
    trace("hit the left");
}

等等...

运算符参考:http ://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/operators.html#conditional

输入你的变量也许是个好主意: var velx:Number = 5; var vely: 数字 = 5;

希望有所帮助。

于 2013-04-15T03:11:56.543 回答