产卵球故障

时间:2018-10-10 04:16:34

标签: javascript canvas html5-canvas

我创建了一个小模拟,当在画布上单击鼠标左键时会产生球,然后球开始掉落。该脚本使用javascript编写:

var ctx = canvas.getContext("2d");

var vy = 0;
var a = 0.5;
var bouncing_factor = 0.9;

var balls = [];
class Ball {
    constructor(x, y, r){
        this.x = x;
        this.y = y;
        this.r = r;
    }

    show () {
        ctx.fillStyle="red";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
        ctx.fill();
    }

    bounce () {
        var ground = canvas.height - this.r;

        if(this.y > ground && Math.abs(vy) < a + 1) {
            cancelAnimationFrame(draw);
        } 
        else if (this.y < ground) {
            vy += a;
            this.y += vy;
        } 
        else {
            vy = -vy * bouncing_factor;
            this.y = ground - 1;
        }
    }
}

function spawn(event) {
    var r = (Math.random()*20)+10;
    var b = new Ball(event.clientX, event.clientY, r);
    balls.push(b);
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (var i = 0; i < balls.length; i++) {
        balls[i].show();
        balls[i].bounce();
    }
}
setInterval(draw,10);

这里的问题是,如果您运行此脚本,那么它对于第一个球就可以正常工作,但是当您生成另一个球时却可以;它是第一个弹跳动作。
任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我在代码中做了一些更改:速度vx和加速度a现在是球对象的一部分。速度从3开始,每次击球时加速度都会降低。当加速度this.a <.1

时,球停止弹跳。

const canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");



var bouncing_factor = 0.9;

var balls = [];
class Ball {
    constructor(x, y, r){
        this.x = x;
        this.y = y;
        this.r = r;
        this.vy = 3;
        this.a = 0.5;
    }

    show () {
        ctx.fillStyle="red";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
        ctx.fill();
    }

    bounce () {
        var ground = canvas.height - this.r;
       
      
       if (this.y < ground) {     
            this.vy += this.a;
            this.y += this.vy;
        } 
        else {
            this.vy = -this.vy * bouncing_factor;
            this.y = ground - 1;
            this.a *=.95;
        }
       
       if(Math.abs(this.a) < .1){this.a=0; this.vy=0}
    }
}

function spawn(event) {
    var r = (Math.random()*20)+10;
    var b = new Ball(event.clientX, event.clientY, r);
    balls.push(b);
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    for (var i = 0; i < balls.length; i++) {
        balls[i].show();
        balls[i].bounce();
    }
}
setInterval(draw,10);


canvas.addEventListener("click", spawn)
<canvas id="myCanvas"  style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>