【问题标题】:Add a keyboard event listener that changes the speedX and speedY using the WASD keys添加一个键盘事件侦听器,使用 WASD 键更改 speedX 和 speedY
【发布时间】:2014-03-12 22:39:59
【问题描述】:

这是我的第一篇文章,我在尝试完成我的代码时遇到了一些麻烦,我已经完成了基础知识,但需要一些指导:有人愿意帮忙吗?

这就是我正在尝试做的事情,但在挣扎:我已经停滞不前了!

添加一个键盘事件侦听器,使用 WASD 键更改 speedX 和 speedY:
'W' 增加 SpeedY 'S' 降低 SpeedY 'A' 降低 SpeedX 'D' 增加 SpeedX

确保 SpeedX 和 Speed Y 永远不会太快

在绘图函数中,使用 speedX 和 speedY 变量更改 x 和 y 位置。

如果圆圈在画布之外,则将其移动到另一侧。例如,如果球在画布的右侧,则将其移动到另一侧。在移动它之前确保球完全离开边缘,否则它可能会弹出。

这是我到目前为止的代码:

var canvas;
var ctx;

var width  = 320;
var height = 240;

var speedX  = 0;    //how fast the ball is moving in the horizontal direction
var speedY  = 0;    //how fast the ball is moving in the vertical direction

var radius  = 10;


var x   = width  / 2  - radius;  //starting horizontal position
var y   = height / 2  - radius;  //starting vertical position


var circleColor             = "#FF0000";

var rectangleColorBg        = "#FFFFFF";
var rectangleColorStroke    = "#000000";


function init() {
    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");
    return setInterval(draw, 10);
}


function circle(x,y,r, color) {
    ctx.fillStyle = color;
    ctx.beginPath();
    ctx.arc(x, y, r, 0, Math.PI*2, true);
    ctx.fill();
}

function rect(x,y,w,h) {
    ctx.fillStyle   = rectangleColorBg;
    ctx.strokeStyle = rectangleColorStroke;
    ctx.beginPath();
    ctx.rect(x,y,w,h);
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
}


function draw() {

  //update based on speedX and speed y
  //update if the ball position is not inside the canvase.

  //draw the background - see function above
  rect(0,0,width,height);
  //
  //draw the circle - see function above
  circle(x, y, radius, circleColor);
}


init();

【问题讨论】:

  • 您的代码中没有键盘事件监听器的痕迹。你已经尝试了什么?
  • 对不起,这是我最基本的代码,我这样发布是因为我的键盘事件监听器似乎不起作用。
  • 您能否将此代码放入 jsfiddle 中,以便我们更轻松地提供帮助?

标签: javascript event-handling keyboard addeventlistener interactive


【解决方案1】:

看看你到目前为止所做的尝试会很有帮助,但这里是事件监听器部分的一些示例代码:

document.addEventListener('keydown', function(event) {
    if(event.keyCode == 37) {
        // Move ('left');
    }
    else if(event.keyCode == 39) {
        // Move ('right');
    }
    else if(event.keyCode == 38) {
        // Move ('up');
    }
    else if(event.keyCode == 40) {
        // Move ('down');
    }
}

您在事件侦听器方面的进展如何?你也可以做'keyup'之类的。

【讨论】:

  • 一些可能有用的游戏代码可以在朋友的 github acct here 上找到。一旦我更好地了解问题并且如果您需要,我很乐意提供更多帮助。
猜你喜欢
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 2011-12-18
  • 1970-01-01
  • 2019-07-05
  • 1970-01-01
  • 1970-01-01
  • 2013-06-29
相关资源
最近更新 更多