Javascript-距离(以像素为单位)-判定
我有一个简单的javascript动画,其中两个牛仔(iamges)根据一个随机间隔数彼此“比赛” 我不知道该怎么做的是让脚本决定谁是赢家,这意味着如果一个牛仔先到达一个预定义的距离,脚本就会知道并显示一个关于谁赢的警告 以下是显示示例的屏幕截图: 这是我目前掌握的代码: 能给我指路吗 谢谢, Brian在Javascript-距离(以像素为单位)-判定,javascript,animation,distance,design-decisions,Javascript,Animation,Distance,Design Decisions,我有一个简单的javascript动画,其中两个牛仔(iamges)根据一个随机间隔数彼此“比赛” 我不知道该怎么做的是让脚本决定谁是赢家,这意味着如果一个牛仔先到达一个预定义的距离,脚本就会知道并显示一个关于谁赢的警告 以下是显示示例的屏幕截图: 这是我目前掌握的代码: 能给我指路吗 谢谢, Brian在move()函数中,您应该执行以下操作 if (x >= dest_x) { alert('player 1 won'); } else if (x2 >= dest_x
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
}
}
/*Y不相关,因为您只在X轴上移动它*/
变量1=100;
变量位置2=100;
var dest=800//或任何给定值
函数move(){
var step1=Math.floor(1+(10*Math.random());
var step2=Math.floor(1+(10*Math.random());
位置1+=步骤1;
位置2+=步骤2;
document.getElementById(“牛仔”).style.left=position1+'px';
document.getElementById(“牛仔二号”).style.left=position2+'px';
if(位置1dest)警报(“获胜者是牛仔1”);
如果(位置2>dest)警报(“获胜者是牛仔2”);
//它们也可能在同一步通过目标值
}
}