gpt4 book ai didi

javascript - 在 html5 Canvas 内按下空格键时为玩家子弹设置动画

转载 作者:行者123 更新时间:2023-11-28 15:47:54 25 4
gpt4 key购买 nike

我想做的基本上是当玩家按下空格键时绘制子弹并为其设置动画。我的问题是子弹动画正确,但是当你按住空格键时会绘制无限的子弹线,这是一个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;
};

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

最佳答案

你需要自己处理自动射击。

向您的坦克对象添加两个属性

       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:当导弹距离太远时,不要摧毁它们:这样做。

只是一个想法:如果玩家升级左右,您可能会提高射击率。您还可以处理佳能的热量,并在过热时降低/停止射击率。

我更新了你的 fiddle ,请参见此处: http://jsfiddle.net/gamealchemist/B2nUs/27/

我还修改了一些东西,正如您将看到的,以便游戏流畅并且现在没有闪烁。
(它与 requestAnimationFrame 配合使用,我纠正了一些缺失的 var,坦克的更新在坦克类内,playerMissile 是一个适当的类,并且更新是基于时间的,因此你的游戏在任何设备上都会表现相同。)

编码愉快!!!

关于javascript - 在 html5 Canvas 内按下空格键时为玩家子弹设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21644531/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com