繁体   English   中英

Javascript-距离(以像素为单位)-决策

[英]Javascript - Distance (in pixels) - Decision

我有一个简单的javascript动画,其中两个牛仔(iamges)根据随机间隔号相互“竞争”。

我不知道该怎么做,是由脚本决定谁是获胜者,这意味着如果牛仔先到达预定距离,脚本就会知道并会显示谁获胜的警报。

这是显示示例的屏幕截图:

在此处输入图片说明

这是我到目前为止的代码: http : //pastebin.com/Cmt4N8c9

能给我一些指示吗?

谢谢,布莱恩

move()函数中,您应该执行以下操作

if (x >= dest_x) {
    alert('player 1 won');
} else if (x2 >= dest_x2) {
    alert('player 2 won');
} else {
    ... continue the loop ... 
}

您最有可能把它抛在后面

document.getElementById("cowboy").style.top  = y+'px';
document.getElementById("cowboy").style.left = x+'px';

document.getElementById("cowboytwo").style.top  = y2+'px';
document.getElementById("cowboytwo").style.left = x2+'px';

顺便说一句,您可能还想检查重复变量上的代码。

例如,AFAIK dest_x和dest_x2都相同。

简单的举动

/* Y is not relevant since you only move it on X axis */

var position1 = 100;
var position2 = 100;

var dest      =  800; //Or any given value

function move() {
    var step1 = Math.floor(1 + (10 * Math.random() ) );
    var step2 = Math.floor(1 + (10 * Math.random() ) );

    position1 += step1;
    position2 += step2;

    document.getElementById("cowboy").style.left     = position1+'px';
    document.getElementById("cowboytwo").style.left = position2+'px';



    if(position1 < dest && position2 < dest) {
        window.setTimeout('move()',100);
    } else {
        //We have the winner
        if(position1 > dest) alert("Winner is Cowboy1");
        if(position2 > dest) alert("Winner is Cowboy2");

        //Its also possible that both of them pass target value at the same step
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM