Javascript 画布按键移动-已断开
我的按键移动似乎中断了,如果我按arr.up/down两次,它就会中断,我无法将元素移回。当我停止按住arr时,元素甚至都不会停止。向上/向下,为什么Javascript 画布按键移动-已断开,javascript,jquery,canvas,Javascript,Jquery,Canvas,我的按键移动似乎中断了,如果我按arr.up/down两次,它就会中断,我无法将元素移回。当我停止按住arr时,元素甚至都不会停止。向上/向下,为什么 rocket = new Image(); x = 50; y = 185; score = 0; velY = 0; speed = 2; y += velY; ctx.drawImage(rocket, x, y); if(e.keyCode == 38) { if(velY < speed) { v
rocket = new Image();
x = 50;
y = 185;
score = 0;
velY = 0;
speed = 2;
y += velY;
ctx.drawImage(rocket, x, y);
if(e.keyCode == 38) {
if(velY < speed) {
velY --;
}
}
if(e.keyCode == 40) {
if(velY < speed) {
velY ++;
}
}
rocket=newimage();
x=50;
y=185;
得分=0;
f=0;
速度=2;
y+=0;
ctx.drawImage(火箭,x,y);
如果(e.keyCode==38){
如果(速度<速度){
弗利——;
}
}
如果(e.keyCode==40){
如果(速度<速度){
vc++;
}
}
预览:我本来可以编辑你的代码,但是你通过链接玩的游戏不起作用:(。我希望我提供的这个代码示例可以帮助你 jsFiddle: javascript
var c = document.getElementById('myCanvas');
var ctx = c.getContext('2d');
var rocket = function()
{
this.Sprite = new Image();
this.Sprite.src = "https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS9zafp1ezdR2lSAxTdjZYe_nPhe6VeKKmAuK-GzWQCSs395WkzNA";
this.XPos = 100;
this.YPos = 100;
}
var player = new rocket();
setInterval(function()
{
ctx.fillRect(0,0,400,400);
ctx.drawImage(player.Sprite, player.XPos, player.YPos);
}, 3);
window.addEventListener("keydown", function(e){
// Left key
if(e.keyCode === 37) {
player.XPos -= 5;
}
// Right key
if(e.keyCode === 39) {
player.XPos += 5;
}
// Up key
if(e.keyCode === 38) {
player.YPos -= 5;
}
// Down key
if(e.keyCode === 40) {
player.YPos += 5;
}
});
此外,在代码中,您正在检查相同的if语句的up和downif(velY
试一试
//向上
如果(e.keyCode==38){
如果(速度<速度){
弗利——;
}
}
//向下
如果(e.keyCode==40){
如果(速度>速度){
vc++;
}
}
检查
。
// Up
if(e.keyCode == 38) {
if(velY < speed) {
velY --;
}
}
// Down
if(e.keyCode == 40) {
if(velY > -speed) {
velY ++;
}
}