最初我使用了var playerPaddle1 = {...},我的乒乓球游戏正在运行,但我想学习更好的OOP技术,所以现在我有:
function Paddle() {
this.x = 50;
this.y = 234;
this.vx = 0;
this.vy = 0;
this.width = 19;
this.height = 75;
this.draw = function() {
var self = this;
var img = new Image();
img.src = 'images/paddle.png';
img.onload = function(){
ctx.drawImage(img, self.x, self.y);
};
};
this.update = function() {
// Divide velocity by FPS before adding it
// onto the position.
this.x += this.vx / FPS;
this.y += this.vy / FPS;
// Collision detection
if ( (this.x) < 0 ) {
this.x = 0;
}
/*if ( (this.x + this.width) > (canvas.width / 2) ) {
this.x = (canvas.width / 2) - this.width;*/
if ( (this.y) < 0 ) {
this.y = 0;
}
if ( (this.y + this.height) > canvas.height) {
this.y = canvas.height - this.height;
}
};
};
var player1Paddle = new Paddle();
现在我的keyboardInput脚本不再适用于拨片了(当按下按键时我的拨片将不再移动。)
window.onkeydown = function( e ) {
e = e || window.event;
var code = e.keyCode;
if ( code === 37 ) {
player1Paddle.vx = -200;
} else if ( code === 38 ) {
player1Paddle.vy = -200;
} else if ( code === 39 ) {
player1Paddle.vx = 200;
} else if ( code === 40 ) {
player1Paddle.vy = 200;
}
};
window.onkeyup = function( e ) {
e = e || window.event;
var code = e.keyCode;
if ( code === 37 ) {
player1Paddle.vx = 0;
} else if ( code === 38 ) {
player1Paddle.vy = 0;
} else if ( code === 39 ) {
player1Paddle.vx = 0;
} else if ( code === 40 ) {
player1Paddle.vy = 0;
}
};
我认为我设置完全相同但使用构造函数而不仅仅是变量对象
答案 0 :(得分:0)
window.onkeydown = function( e ) {
e = e || window.event;
var code = e.keyCode;
if ( code === 37 ) {
player1Paddle.vx = -200;
} else if ( code === 38 ) {
player1Paddle.vy = -200;
} else if ( code === 39 ) {
player1Paddle.vx = 200;
} else if ( code === 40 ) {
player1Paddle.vy = 200;
}
player1Paddle.update(); // you forget to tell it to do something with the new info!
player1Paddle.draw();
};
window.onkeyup = function( e ) {
e = e || window.event;
var code = e.keyCode;
if ( code === 37 ) {
player1Paddle.vx = 0;
} else if ( code === 38 ) {
player1Paddle.vy = 0;
} else if ( code === 39 ) {
player1Paddle.vx = 0;
} else if ( code === 40 ) {
player1Paddle.vy = 0;
}
player1Paddle.update(); // you forget to tell it to do something with the new info!
player1Paddle.draw();
};