算法
先看下效果吧:
代码如下:
/*
请教大家一个关于势函数用到追踪和拦截的算法
有研究过的能不能指点一下!
Powered By Sunday
Email:happyclub@163.com
*/
var stepAngle:Number = 3;
//角度最大增量
var tempNum:Number = 0;
var radius:Number = 100;
//导弹飞行半径
var M_speed:Number = 3;
//导弹速度(非常量)
var P_speed:Number = 5;
//飞机速度
findToHit(missile, target);
function findToHit(missile, target) {
missile.onEnterFrame = function() {
_root.AngText = stepAngle;
if (missile.hitTest(target.hit)) {
target.play();
missile._visible = false;
delete missile.onEnterFrame;
}
//---------------击中目标
tempNum++;
if (tempNum == 15) {
if (stepAngle == 2) {
if (Math.abs(target._x-missile._x)>radius*2 || Math.abs(target._y-missile._y)>radius*2) {
stepAngle = 3;
}
} else if ((Math.abs(target._x-missile._x)<30 || Math.abs(target._y-missile._y)<30)) {
stepAngle = 2;
}
tempNum = 0;
}
//---------------------改变角度增量-------------------------
P = new Object();
P.x = missile.way._x;
P.y = missile.way._y;
missile.localToGlobal(P);
dx = P.x-missile._x;
dy = P.y-missile._y;
dx1 = target._x-P.x;
dy1 = target._y-P.y;
//----------------------取得向量--------------------------
angle = Math.atan2(dy1, dx1)*180/Math.PI;
//-----------------------取得角度------------------------
angle = angle<=0 ? Math.abs(360+angle) : angle;
M_angle = missile._rotation<0 ? 360+missile._rotation : missile._rotation;
if (Math.abs(M_angle-angle)>stepAngle) {
if (angle-M_angle>180) {
M_angle += -stepAngle;
} else {
M_angle += angle<M_angle && (M_angle-angle<180) ? -stepAngle : +stepAngle;
}
missile._rotation = M_angle;
}
//---------------------改变导弹角度-----------------------
missile._x += dx*M_speed/10;
missile._y += dy*M_speed/10;
//-----------------------导弹移动---------------------
};
}
//-----------------------------追踪---------------------
listen = new Object();
listen.onKeyDown = function() {
onEnterFrame = function () {
if (Key.isDown(Key.RIGHT)) {
target._x += P_speed;
} else if (Key.isDown(Key.LEFT)) {
target._x -= P_speed;
} else if (Key.isDown(Key.UP)) {
target._y -= P_speed;
} else if (Key.isDown(Key.DOWN)) {
target._y += P_speed;
}
};
};
Key.addListener(listen);
//----------------------------键盘控制--------------------------
看看源文件: 游戏中导弹追踪算法.rar