【问题标题】:Particles won't accelerate?粒子不会加速?
【发布时间】:2016-05-12 20:36:14
【问题描述】:

我正在尝试使用 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();
    }
}

【问题讨论】:

    标签: javascript html5-canvas particles


    【解决方案1】:

    您的绘图函数正在使用传递给构造函数的yVel。 试试this.y += this.yVel;

    【讨论】:

      【解决方案2】:

      看起来您的绘图函数使用的是构造函数中的 xVel 和 yVel,而不是粒子实例中的。尝试将this.y += yVel 更改为this.y += this.yVel

      【讨论】:

        【解决方案3】:

        您可以创建一个名为 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/

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多