gpt4 book ai didi

JavaScript Canvas : Pong - Animation

转载 作者:行者123 更新时间:2023-11-30 16:31:01 25 4
gpt4 key购买 nike

我是 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com