javascript - 生成球故障
问题描述
我创建了一个小型模拟,当鼠标左键单击画布时,球会生成,然后球开始下落。该脚本是用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);
这里的问题是,如果你运行这个脚本,它对第一个球运行良好,但是当你生成另一个球时;它遵循第一个弹跳。
任何帮助将不胜感激。
解决方案
我在您的代码中做了一些更改:速度 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>
推荐阅读
- modelica - 管道直径对模拟速度的影响 - Modelica
- sql - 如何使用连接性能修复 postgresql 更新?
- sas - 从 SAS 上的一行 CSV 数据创建表
- r - r:如何使用带有 sf 几何列的 data.table 包?
- lua - || 在 roblox 上使用 Humanoid:MoveTo() 时出错
- apache-spark - 是否可以获得正在运行的 Spark 任务的尝试次数?
- laravel - 如何解决此错误,此路由不支持 GET 方法。支持的方法:POST
- python-3.x - ValueError:没有足够的值在 tfds.load 中解压
- google-sheets - 创建查询公式
- python - 使用 Python 进行坐标变换时的蒙特卡洛积分