0

最初我使用 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();

现在我的键盘输入脚本不再适用于桨(当我按下键时我的桨将不再移动)。

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;
    }
};

我以为我将其设置为完全相同,但使用构造函数而不是变量对象

4

1 回答 1

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();
};
于 2013-07-21T23:24:22.670 回答