15.2.6 创建setDirection方法

  现在,必须找到一种方法来设置求的方向。我们使用一个名为setDirection的方法来做到这一点。该方法将由keydown事件处理程序来调用,我们将在下一小节介绍keydown。Keydown事件处理程序通过传递给setDirection一个字符串(”left”、”up”、”right”、”down”或”stop”),告诉它按下哪一个键。根据该字符串,setDirection将修改球的xSpeed和ySpeed属性,使其朝着和按键一致的方向移动。例如,如果传递了字符串”down”,我们将this.xSpeed设置为0,将this.ySpeedy设置为5.在draw方法的后面,添加这段代码:

Ball.prototype.setDirection = function (direction) {
if (direction === "up") {
this.xSpeed = 0;
this.ySpeed = -5;
} else if (direction === "down") {
this.xSpeed = 0;
this.ySpeed = 5;
} else if (direction === "left") {
this.xSpeed = -5;
this.ySpeed = 0;
} else if (direction === "right") {
this.xSpeed = 5;
this.ySpeed = 0;
} else if (direction === "stop") {
this.xSpeed = 0;
this.ySpeed = 0;
}
};

  整个方法体就是一条很长的if……else语句。新的方向作为direction参数传入到该方法中。如果direction等于”up”,我们将球的xSpeed属性设置为0,将ySpeed属性设置为-5。其他的方向也以相同的方式来处理。最后,如果方向设置为字符串”stop”,我们将this.xSpeed和this.ySpeed都设置为0,这意味着球将会停止移动。


本站内容未经许可,禁止任何网站及个人进行转载。

   口袋儿题库-青少儿编程自测题库