【问题标题】:canvas game| how to control fire rate?画布游戏|如何控制射速?
【发布时间】:2017-10-12 23:07:17
【问题描述】:

目前我的代码每秒创建一个子弹 60 次 (setInterval) 我尝试过 for 循环,但根本没有用。 有谁知道如何调节射速?

谢谢。

【问题讨论】:

  • 欢迎来到Stack Overflow!在此站点上,您应该尝试自己编写代码。在 doing more research 之后,如果您有问题,您可以发布您尝试过的内容,并清楚地解释什么不起作用并提供Minimal, Complete, and Verifiable example。我建议阅读How to Ask 一个好问题和the perfect question。另外,请务必使用tour 并阅读this
  • 你已经asked 一个没有代码的低质量问题,向我们展示你的代码
  • @AlonEitan 是什么让像这样的问题获得如此多的投票而被关闭,而像这样的问题 stackoverflow.com/q/2142535/3877726 得到保护?在我看来,抽签的运气才是好问题。
  • @Blindman67 抱歉回复晚了,但这个问题已经有 7 年多了。时代变了,今天问同样的问题也会让你被否决和关闭。我认为赞成来自这个问题在谷歌搜索中排名很高。不过我确实喜欢你的回答!
  • @Blindman67 关于受保护的问题 - 阅读this comment 可能的原因

标签: javascript html canvas


【解决方案1】:

在大多数实时游戏中,您都会有一个主循环来控制动画。您可以为此添加火控。

// object to hold details about the gun
const gun = {
    fireRate : 2,  // in frames (if 60 frames a second 2 would be 30 times a second
    nextShotIn : 0, // count down timer till next shot
    update() {  // call every frame
        if(this.nextShotIn > 0){
            this.nextShotIn -= 1;   
        }
    }, 
    fire(){
        if(this.nextShotIn === 0){
            // call function to fire a bullet
            this.nextShotIn = this.fireRate; // set the countdown timer
         }
    }
}


function mainAnimationLoop()
     // game code


     gun.update();
     if(fireButtonDown){
         gun.fire(); // fire the gun. Will only fire at the max rate you set with fireRate
     }


     // rest of game code
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    相关资源
    最近更新 更多