JavaScript Canvas: Pong - Animation

JavaScript Canvas: Pong - Animation

本文关键字:Animation Pong Canvas JavaScript      更新时间:2023-09-26

我是HTML 5 + Canvas游戏开发新手,尝试在我的Pong游戏中动画球。这是我的代码。相关片段:

增加球的速度:

Ball.prototype.update = function () {
    this.x += this.velocity.x;
    this.y += this.velocity.y;
};

游戏循环代码:

function update() {
    ball.update();
    window.requestAnimationFrame(update);
}

球只是坐在那里。我在谷歌上搜索过,也读过几篇文章,但运气不好。如果你能帮我把球移开,我会很感激的。

jsfiddle演示

删除render()函数,因为不需要(将所有内容移到update()),您需要

  • 清除画布以重新绘制
  • 再次"渲染"所有更新的元素对象在画布上的每个关键帧(不只是在init)

var canvas = document.createElement("canvas");
var ctx = canvas.getContext('2d');
function init(width, height, bg) {

    canvas.width = width;
    canvas.height = height;
    canvas.style.backgroundColor = bg;
    document.body.appendChild(canvas);

    function Paddle(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.velocity = {
            x: 0,
            y: 0
        };
    }
    Paddle.prototype.render = function () {
        ctx.fillStyle = 'rgb(2, 149, 212)';
        ctx.fillRect(this.x, this.y, this.width, this.height);
    };
    function Player() {
        this.paddle = new Paddle(485, canvas.height / 2 - 25, 15, 50);
    }
    Player.prototype.render = function () {
        this.paddle.render();
    };
    function AI() {
        this.paddle = new Paddle(0, canvas.height / 2 - 25, 15, 50);
    }
    AI.prototype.render = function () {
        this.paddle.render();
    };
    function Ball(x, y, radius) {
        this.x = x;
        this.y = y;
        this.radius = radius;
        this.velocity = {
            x: 2,
            y: 2
        };
    }
    Ball.prototype.render = function () {
        ctx.beginPath();
        ctx.fillStyle = 'rgb(80, 80, 80)';
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
        ctx.fill();
    };
    Ball.prototype.update = function () {
        this.x += this.velocity.x;
        this.y += this.velocity.y;
    };
    window.player = new Player();
    window.computer = new AI();
    window.ball = new Ball(canvas.width / 2, canvas.height / 2, 10);
}
function update() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    player.render();
    computer.render();
    ball.update();
    ball.render();
    window.requestAnimationFrame(update);
}
function main() {
    init(500, 250, '#EEE');
    update();
}
main();