我是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");
}
}
答案 0 :(得分: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
输入你的vars也许是一个好主意: var velx:Number = 5; var vely:Number = 5;
希望有所帮助。