在击中html5画布内的空格键时动画播放器子弹

时间:2014-02-08 09:55:31

标签: javascript jquery html5

我想要做的基本上是在玩家击中空格键时绘制和动画子弹。我的问题子弹正确动画但是当你按住空格键时会画出无限的子弹线这是一个jsfiddle可以解释我的意思:http://jsfiddle.net/seekpunk/B2nUs/26/

代码:

   var Missiles = {
            collection: [],

            draw: function () {
                for (i = 0; i < this.collection.length; i++) {
                    this.collection[i].draw();
                    // Missiles.collection.length = 0;
                }
            },
            update: function () {
                if (Missiles.collection.length > 0) {
                    for (i = 0; i < Missiles.collection.length; i++) {

                        Missiles.collection[i].update();
                        // Missiles.collection.length = 0;
                    }
                }

            }

        };
        var playerMissile = function (M) {
            Mx = this.x;
            My = this.y;
            MR = this.radius;
            Msp = 3;
            MDir = this.rot;
            M.draw = function () {
                ctx.fillStyle = "Green";
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, true);
                ctx.closePath();
                ctx.fill();
                //this.h*2 specify that the image is in the row 2 of the tiled image
            };
            M.update = function () {

                switch (this.rot) {
                    case 0: this.y -= 3; break;
                    case 90: this.x += 3; break;
                    case -90: this.x -= 3; break;
                    case 180: this.y += 3; break;
                }


            };
            return M;
        };

即使用户按住空格键,我怎样才能在每个空格键上绘制一个子弹,这样我就可以阻止这一连续子弹线

2 个答案:

答案 0 :(得分:4)

您需要自己处理自动火灾。

向坦克对象添加两个属性

       lastShootTime : 0,  // time when we last shoot 
       shootRate : 300,    // time between two bullets. (in ms)

然后,只有在自上次拍摄后经过足够时间时拍摄:

       shoot: function () {
           var now = Date.now() ;
           if (now - this.lastShootTime  < this.shootRate)  return;
           this.lastShootTime  = now ;
           Missiles.collection.push(playerMissile({
               x: this.x,
               y: this.y,
               radius: 2,
               rot: this.rotation
           }));
       }

Rq1:处理每枚导弹的速度,并在导弹上增加坦克速度,以避免坦克在自己的导弹上行进(或者快速加速导弹以便快速修复。)

Rq 2:当它们太远时你不会摧毁导弹:做它。

只是一个想法:如果玩家获得升级,你可以改善shootRate。你也可以处理佳能的热量,并使射击率下降/停止过热。

我更新了你的小提琴,请看这里: http://jsfiddle.net/gamealchemist/B2nUs/27/

我还会修改一些内容,正如您将看到的那样,以便游戏顺畅,现在没有闪烁。
(它适用于requestAnimationFrame,我更正了一些var缺失,tank的更新在tank类中,playerMissile是一个合适的类,并且更新是基于时间的,因此你的游戏在任何设备上的行为都相同。)

快乐的编码!!!

答案 1 :(得分:0)

尝试使用keyup事件,因为keydown会持续触发,keyup会触发一次......