我正在尝试制作一组人类/细菌相互追逐的应用程序。但是,如果我试图让它们直接向目标移动,它们都会向左移动。(我说“目标”是因为一侧以另一侧的成员为目标。)我尝试使用三角函数,其中您具有初始 x,y 坐标,但我必须找到下一个 x,y 坐标以及要行驶的坡度和距离已知。这是我的相关代码:
/*Functions for calculating next x, y*/
function calculate_nextX(startx, length, slope)
{
var x = 0;
var degree = Math.atan(slope);
x = (startx + (length * Math.sin(degree * 0.0174)));
return x;
}
function calculate_nextY(starty, length, slope)
{
var y = 0;
var degree = Math.atan(slope);
y = (starty + (length * Math.cos(degree * 0.0174)));
return y;
}
/*Where the functions get used*/
function updateeverything()
{
for(var i=0;i<=49;i++)
{
if(bacteriaGroup[i].dead == false)
{
if(humanGroup[bacteriaGroup[i].target].dead == true)
{
bacteriaGroup[i].target = settarget(true,i);
}
var left = parseInt(document.getElementById("bacteria"+i).style.left);
var left1 = parseInt(document.getElementById("human"+bacteriaGroup[i].target).style.left);
var top = parseInt(document.getElementById("bacteria"+i).style.top);
var top1 = parseInt(document.getElementById("human"+bacteriaGroup[i].target).style.top);
var finalleft = calculate_nextX(left,1,(top1-top)/(left1-left));
var finaltop = calculate_nextY(top,1,(top1-top)/(left1-left));
document.getElementById("bacteria"+i).style.left = finalleft;
document.getElementById("bacteria"+i).style.top = finaltop;
}
if(humanGroup[i].dead == false)
{
if(bacteriaGroup[humanGroup[i].target].dead == true)
{
humanGroup[i].target = settarget(false,i);
}
var left = parseInt(document.getElementById("human"+i).style.left);
var left1 = parseInt(document.getElementById("bacteria"+humanGroup[i].target).style.left);
var top = parseInt(document.getElementById("human"+i).style.top);
var top1 = parseInt(document.getElementById("bacteria"+humanGroup[i].target).style.top);
var finalleft = calculate_nextX(left,1,(top1-top)/(left1-left));
var finaltop = calculate_nextY(top,1,(top1-top)/(left1-left));
document.getElementById("human"+i).style.left = finalleft;
document.getElementById("human"+i).style.top = finaltop;
}
}
}