粒子不会加速?
Particles won't accelerate?
我正在尝试使用 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();
}
}
看起来您的绘图函数使用的是构造函数中的 xVel 和 yVel,而不是粒子实例中的。尝试将 this.y += yVel
更改为 this.y += this.yVel
。
您的绘图函数正在使用传递给构造函数的 yVel
。
试试 this.y += this.yVel;
您可以创建名为 speed 的额外变量,然后像这样加速球:
function Particle(xVel, yVel) {
this.xVel = xVel;
this.yVel = yVel;
this.speed = 1;
this.x = canvas.width/2;
this.y = canvas.height/2;
this.draw = function() {
this.x += this.speed * this.xVel;
this.y += this.speed * this.yVel;
this.speed++;
ctx.beginPath();
ctx.arc(this.x, this.y, 1, 0, Math.PI * 2);
ctx.fillStyle = "rgb(0, 255, 0)";
ctx.fill();
}
}
这是 jsfiddle 上的示例 https://jsfiddle.net/3nnm2omm/
我正在尝试使用 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();
}
}
看起来您的绘图函数使用的是构造函数中的 xVel 和 yVel,而不是粒子实例中的。尝试将 this.y += yVel
更改为 this.y += this.yVel
。
您的绘图函数正在使用传递给构造函数的 yVel
。
试试 this.y += this.yVel;
您可以创建名为 speed 的额外变量,然后像这样加速球:
function Particle(xVel, yVel) {
this.xVel = xVel;
this.yVel = yVel;
this.speed = 1;
this.x = canvas.width/2;
this.y = canvas.height/2;
this.draw = function() {
this.x += this.speed * this.xVel;
this.y += this.speed * this.yVel;
this.speed++;
ctx.beginPath();
ctx.arc(this.x, this.y, 1, 0, Math.PI * 2);
ctx.fillStyle = "rgb(0, 255, 0)";
ctx.fill();
}
}
这是 jsfiddle 上的示例 https://jsfiddle.net/3nnm2omm/