[英]Particles won't accelerate?
I'm trying to make particles that accelerate using JavaScript and the HTML5 Canvas, but I cannot get them to accelerate, they just move at a constant speed. 我正在尝试使用JavaScript和HTML5 Canvas来使粒子加速,但是我无法使其加速,它们只是以恒定的速度运动。 Does anyone know why?
有人知道为什么吗?
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();
}
}
Your draw function is using the yVel
passed to the constructor. 您的绘制函数正在使用传递给构造函数的
yVel
。 try with this.y += this.yVel;
尝试
this.y += this.yVel;
It looks like your draw function is using the xVel and yVel from the constructor instead of from the particle instance. 看起来您的绘制函数正在使用构造函数而不是粒子实例中的xVel和yVel。 Try changing
this.y += yVel
to this.y += this.yVel
. 尝试将
this.y += yVel
为this.y += this.yVel
。
You can create extra variable with name speed and then speed up the balls like this: 您可以使用名字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();
}
}
Here is example on jsfiddle https://jsfiddle.net/3nnm2omm/ 这是jsfiddle https://jsfiddle.net/3nnm2omm/上的示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.