JavaScript Canvas : Pong - Animation

标签 javascript html canvas html5-canvas

我是 HTML 5 + Canvas 游戏开发新手。试图在我的 Pong 游戏中为球制作动画。这是我的 code .相关片段:

增加球的速度:

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

游戏循环代码:

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

球只是停在那里。我用谷歌搜索并阅读了几篇文章,但没有运气。如果您能帮助我移动球,我将不胜感激。

最佳答案

jsfiddle demo

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

  • 清除 Canvas 以重绘
  • 在 Canvas 上的每个关键帧(不仅仅是在初始化时)再次“渲染”所有更新的元素对象

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();

关于JavaScript Canvas : Pong - Animation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33324707/

相关文章:

html - Safari 中的元素未正确对齐

javascript - 如何清除图像以便重绘?

Javascript 更改下拉列表值

javascript - 如何使用 Javascript 从伪元素获取 FontAwesome 字符代码

html - 跨浏览器输入字段宽度设置不正确

javascript - 即时客户端图像到 webp 转换器......但 png 不透明

javascript - 当我将 SVG 内容绘制到 Canvas 时,SVG 被裁剪

javascript - 是否可以将 php 变量分配给 jquery var,然后刷新该 jquery 变量

javascript - 如果在 Bootstrap-Select 中不存在搜索,则添加新选项

html - 使用 Bootstrap 在一排类(class)中只获得一个分区中心