首页 > 解决方案 > 生成球故障

问题描述

我创建了一个小型模拟,当鼠标左键单击画布时,球会生成,然后球开始下落。该脚本是用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);

这里的问题是,如果你运行这个脚本,它对第一个球运行良好,但是当你生成另一个球时;它遵循第一个弹跳。
任何帮助将不胜感激。

标签: javascriptcanvashtml5-canvas

解决方案


我在您的代码中做了一些更改:速度 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>


推荐阅读