我正在制作一个基本的游戏http://www.jasonhuman.co.za/lazerlazer
这个想法是了解更多关于javascript和画布的信息
。我遇到的问题是我在正文元素上绑定了键压它只允许一次拿起一个按键而且它并不是那么顺利 - 船在开始运动之前滞后了一秒钟
我怎样才能使船立即开始向正确的方向移动一旦按键发生?
这是我控制按键事件的代码:
function keyPress(e){
//w=119, s = 115, a = 97, d = 100
if(e.charCode==119){
player[0].ypos -=15;
playerImg.src = 'images/playerUp.png';
engines.play();
}
if(e.charCode==115){
player[0].ypos +=15;
playerImg.src = 'images/playerDown.png';
engines.play();
}
if(e.charCode==97){
player[0].xpos-=15;
playerImg.src = 'images/playerFW.png';
engines.play();
}
if(e.charCode==100){
player[0].xpos+=15;
playerImg.src = 'images/playerFW.png';
engines.play();
}
//fire a bullet
if(e.charCode==32)
{
//fire a bullet
bullets.push(new init(player[0].xpos+88,player[0].ypos+25));
//gunshots
var gunshot = new Audio('lazer.mp3');
gunshot.play();
}
}
正如@Rob Baille所说,监听键下而不是按键事件。
延迟是由于每次按键都重新加载图像。
而是只预加载一次所有图像。
然后根据需要在密钥处理程序中将playerImg
设置为适当的图像。
另外,您重复了图像/播放器FW.png...这是故意的吗?
下面是使用图像预加载器重构的代码的示例:
// image loader
var imageURLs=[]; // put the paths to your images here
var imagesOK=0;
var imgs=[];
imageURLs.push("images/playerUp.png");
imageURLs.push("images/playerDown.png");
imageURLs.push("images/playerFW.png");
imageURLs.push("images/playerFW.png");
loadAllImages(start);
function loadAllImages(callback){
for (var i=0; i<imageURLs.length; i++) {
var img = new Image();
imgs.push(img);
img.onload = function(){
imagesOK++;
if (imagesOK>=imageURLs.length ) {
callback();
}
};
img.onerror=function(){alert("image load failed");}
img.crossOrigin="anonymous";
img.src = imageURLs[i];
}
}
function start(){
// All images have been fully pre-loaded
// Allow the game to begin
// Maybe hide the "Play" button until this function is triggered
}
function keyPress(e){
//w=119, s = 115, a = 97, d = 100
if(e.charCode==119){
player[0].ypos -=15;
playerImg = imgs[0];
engines.play();
}
if(e.charCode==115){
player[0].ypos +=15;
playerImg = imgs[1];
engines.play();
}
if(e.charCode==97){
player[0].xpos-=15;
playerImg = imgs[2];
engines.play();
}
if(e.charCode==100){
player[0].xpos+=15;
playerImg = imgs[3];
engines.play();
}
//fire a bullet
if(e.charCode==32)
{
//fire a bullet
bullets.push(new init(player[0].xpos+88,player[0].ypos+25));
//gunshots
var gunshot = new Audio('lazer.mp3');
gunshot.play();
}
}
嗯,关于如何处理这个问题,我有两种方法。您可以更频繁地更新帧,也可以使用其他按键按下方法。更快地更新帧
var sim_interval = 1 / 40; // number of times per second that we step the animation.
如上所述,这将我们每秒步进动画的次数声明为变量。接下来的代码是如何重新编辑初始状态。
render(); // render the initial state.
interval_callback_id = window.setInterval(step, sim_interval); // set the callback and save the identifier.
}
每个更红的代码都会有点不同,你的函数 render(){ 可能不同,它是如何更新系统。另一种执行键向下方法的方法可以在这里找到 如何在 JS 中使用空格键和 if 语句?