我是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);
}
球只是坐在那里。我已经用Google搜索并阅读了几篇文章,但没有运气。我希望能帮助球移动。
最佳答案
jsfiddle demo
删除了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();