【问题标题】:Game time in Javascript Browser GameJavascript 浏览器游戏中的游戏时间
【发布时间】:2022-06-10 20:25:07
【问题描述】:

说实话,我对 javascript 和编程还很陌生。我知道 html 和 css 以及 javascript 的基础知识,我正试图弄清楚时间在 js 中是如何工作的。

我想制作一个简单的游戏,用户可以在其中照顾一匹马。他所做的每一个动作(即刷鬃毛)都需要一定的时间。让我们说五分钟。我该如何编码?

如果有人能告诉我,将非常感激。提前谢谢你。

快乐

【问题讨论】:

    标签: javascript time


    【解决方案1】:

    只是在未来的时间里完成比赛。

    使用这个功能

    function getTime(numOfHours) {
       let date = new Date();
      date.setTime(date.getTime() + numOfHours * 60 * 60 * 1000);
      return date;
    }
    

    然后检查您的游戏逻辑以查看事件结束时间是否与当前时间相对。

    let endEventTime = getTime(0,00138); // add 5 seconds to the current time
    // do a loop or some setTimeout() login and once the time passes then let your user do another action.
    

    【讨论】:

      【解决方案2】:

      这是一种方法:制作每帧都运行的东西,然后根据它更改时间。这是一个小例子:(cmets 解释了它是如何工作的)

      // at the start of the program, set a number called 'time' to zero
      let time = 0
      
      // it takes 18000 frames to brush a horse
      let time_it_takes_to_brush_a_horse = 18000
      
      
      /* this function runs every frame thanks to the
      requestAnimationFrame() at the bottom of it.
      requestAnimationFrame() tells the computer to
      run the function again once its finished */
      
      function update() {
          /* because we are inside a function that runs
          every frame (60fps), telling time to add 1 to
          itself means it will grow by 1 every frame. */
          time = time + 1
      
          // if the time is at five minutes, print some text to the browser console
          if (time == time_it_takes_to_brush_a_horse) {
              console.log('You have finished brushing the horses mane')
          }
      
          requestAnimationFrame(update)
      }
      
      // run the update() function at the start of the program
      update()
      

      【讨论】:

      • 这对我来说实际上听起来不错。我可以想象它工作。但这是否意味着现实生活中的五分钟?
      • 是的,它会的。如果您希望它更快,请将 time_it_takes_to_brush_a_horse 更改为较小的数字。例如,1000 意味着您只需要刷马大约 16 秒。祝您的项目一切顺利!
      猜你喜欢
      • 2016-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多