【问题标题】:Javascript - Distance (in pixels) - DecisionJavascript - 距离(以像素为单位) - 决定
【发布时间】:2012-11-08 13:20:49
【问题描述】:

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

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

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

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

能给我一些指示吗?

谢谢, 布赖恩

【问题讨论】:

    标签: javascript animation distance design-decisions


    【解决方案1】:

    在您的 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 都是相同的。

    【讨论】:

      【解决方案2】:

      简单的动作

      /* 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
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2016-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多