我想创建一个基本的物理沙箱应用程序,使用 matter.js 作为物理引擎和 p5.js 进行渲染。我的想法是在按下特定按钮时生成物体(左键用于弹力物体,右键用于重物体等)。我使用此代码进行关键控制:
if (keyIsDown(LEFT_ARROW)) {
rubber2 = new Rubber(100,40,15)
rubber2.display()
}
rubber2.display();
这是
Rubber
类:
class Rubber {
constructor(x, y, r) {
var options = {
'restitution': 1.5,
'density': 0.9,
'friction': 1
}
this.x = x;
this.y = y;
this.r = r
this.body = Bodies.circle(this.x, this.y, (this.r - 20) / 2, options)
World.add(world, this.body);
}
display() {
var rubberpos = this.body.position;
push()
translate(rubberpos.x, rubberpos.y);
rectMode(CENTER)
strokeWeight(4);
stroke("green");
fill("yellow");
ellipse(0, 0, this.r)
pop()
}
}
这给了我像
rubber2 is not defined
或 rubber2
身体仅在按住键时显示并且没有任何物理特性的错误。根本不展示球确实会产生身体,但它们是看不见的。
你展示的代码看起来很合理,所以仍然不足以真正重现你可能遇到的问题。清理并将其变成可运行的示例后,我可以提供:
class Rubber {
constructor(x, y, r, engine) {
const options = {
restitution: 1.5,
density: 0.9,
friction: 1,
};
this.body = Matter.Bodies.circle(x, y, r, options);
Matter.Composite.add(engine.world, this.body);
}
display() {
const {position: {x, y}, circleRadius: r} = this.body;
push();
translate(x, y);
strokeWeight(4);
stroke("green");
fill("yellow");
ellipse(0, 0, r * 2);
pop();
}
}
let rubbers = [];
let engine;
function setup() {
createCanvas(500, 200);
engine = Matter.Engine.create();
}
function draw() {
if (keyIsDown(LEFT_ARROW)) {
rubbers.push(new Rubber(mouseX, mouseY, 15, engine));
}
background(30);
rubbers = rubbers.reduce((nextGen, e) => {
const {position: {x, y}, circleRadius} = e.body;
if (y + circleRadius <= height) {
nextGen.push(e);
e.display();
}
return nextGen;
}, []);
Matter.Engine.update(engine);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.6.0/p5.min.js"></script>
<p>Press the left arrow key to create a ball where the mouse is</p>