1

我正在尝试制作一组​​人类/细菌相互追逐的应用程序。但是,如果我试图让它们直接向目标移动,它们都会向左移动。(我说“目标”是因为一侧以另一侧的成员为目标。)我尝试使用三角函数,其中您具有初始 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;
        }
    }
}
4

2 回答 2

1

表达方式

(top1-top)/(left1-left)

无论目标是向上和向左还是向下和向右,都具有相同的值。这可能是您问题的根源。

我提议:

var distance_to_target = sqrt((top1-top)*(top1-top) + (left1-left)*(left1-left));
var fraction_of_distance = length / distance_to_target;
var dx = (left1 - left) * fraction_of_distance;
var dy = (top1 - top) * fraction_of_distance;

另请注意,css 位置会四舍五入到最接近的整数,因此如果您移动少量,则需要对逻辑位置进行处理,然后在最后将它们四舍五入。

于 2013-01-17T05:32:44.710 回答
0

slope不区分上下移动/左右移动 - 它只是 的比率x/y。要获得degree,您需要两者xyvalue 并且需要使用该atan2函数(在 JS 中,Math.atan2)。

但是,我完全没有理由使用度数作为方向。您可以使用简单的勾股定理轻松(并且更快)计算下一个坐标。

于 2013-01-17T06:02:32.747 回答