我正在尝试制作使用JavaScript和HTML5 Canvas加速的粒子,但我不能让它们加速,它们只是以恒定速度移动。有谁知道为什么?
document.addEventListener("DOMContentLoaded", init);
function init() {
canvas = document.getElementById("canvas");
ctx = canvas.getContext("2d");
angle = Math.random() * (2 * Math.PI);
pArray = [];
for (i = 0; i<25; i++) {
angle = Math.random() * (2*Math.PI);
pArray[i] = new Particle(Math.cos(angle), Math.sin(angle));
}
setInterval(loop, 50);
}
function loop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (x = 0; x < pArray.length; x++) {
pArray[x].draw();
}
}
function Particle(xVel, yVel) {
this.xVel = xVel;
this.yVel = yVel;
this.x = canvas.width/2;
this.y = canvas.height/2;
this.draw = function() {
this.x += xVel;
this.y -= yVel;
this.yVel += 1;
ctx.beginPath();
ctx.arc(this.x, this.y, 1, 0, Math.PI * 2);
ctx.fillStyle = "rgb(0, 255, 0)";
ctx.fill();
}
}
答案 0 :(得分:3)
您的绘图函数使用传递给构造函数的yVel
。
试试this.y += this.yVel;
答案 1 :(得分:2)
看起来你的绘图函数正在使用构造函数中的xVel和yVel而不是粒子实例。尝试将this.y += yVel
更改为this.y += this.yVel
。
答案 2 :(得分:0)