在垂直移动图像时遇到用户输入问题

时间:2015-04-19 20:01:15

标签: javascript html image user-input

我需要通过用户输入垂直移动图像,但是当我按下定义的键时没有任何反应。我不知道我用来绘制垂直新图像的命令是错误的还是我的功能是什么?

的script.js

var map = document.getElementById("map");
var ctx = map.getContext("2d");

var baseImage = new Image();
baseImage.src = "assets/base.png";
baseImage.addEventListener("load", drawImage);

var speedyImage = new Image();
speedyImage.src = "assets/speedy.png";
speedyImage.addEventListener("load", drawImage);

var bubbleImage = new Image();
bubbleImage.src = "assets/bubble.png";
bubbleImage.addEventListener("load", drawImage);

document.addEventListener('keydown', function(event){ handleKeyPress(event);});

var dt = 1000/30.0;

function intersectRect(r1, r2) { // detects collision

    return !(r2.left > r1.right ||
    r2.right < r1.left ||
    r2.top > r1.bottom ||
    r2.bottom < r1.top);
}

function drawImage(){
    setInterval(update, 1000/30.0);
}

var x = 0;
var y = 0;
var speed = 0.05;
var direction = 1;
document.getElementById("score").innerHTML = 0;

function update(){
    ctx.clearRect(0, 0, map.width, map.height);

    for(var i = 0; i < 1; i++){
            ctx.drawImage(bubbleImage,x, map.height - baseImage.height - 50);
            function handleKeyPress(event){
                if(event.keyCode == 32){ // if space
                                    // trouble here... would I just use the draw image function again?          

                }
            }
    }

    for(var i = 0; i < 3; i++){
            ctx.drawImage(speedyImage,x,0);
            ctx.drawImage(speedyImage,x,70);
            ctx.drawImage(speedyImage,x,150);
        if(intersectRect(bubbleImage,speedyImage) == false)
            score+= score+100;
    }

    ctx.drawImage(baseImage, x, map.height - baseImage.height );
    y += speed*direction*dt;
    x += speed * direction * dt;    

    if (x > map.width - baseImage.width || x < 0)
        direction = -direction;
}

1 个答案:

答案 0 :(得分:0)

您尚未声明handlekeyPress(event)功能。

   for(var i = 0; i < 1; i++){
        ctx.drawImage(bubbleImage,x, map.height - baseImage.height - 50);
        function handleKeyPress(event){
            if(event.keyCode == 32){ // if space
                                // trouble here... would I just use the draw image function again?          

            }
        }
}

如图所示,您在另一个函数中指定了函数代码。因此,无法在函数外部调用此函数。