我正在试着画多个 pyramid 形状的圆,就像这样:balls in pyramid shape
我上了这堂"Balls"课:
class Balls {
constructor(x, y, radius, color, ballCount) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.balls = [];
this.ballCount = ballCount;
this.option = { restitution: 1, friction: 0.01, label: "ball" };
}
setupBalls() {
for (var i = 0; i < this.ballCount; i++) {
var ball = Bodies.circle(this.x, this.y , this.radius, this.option);
this.balls.push(ball);
World.add(engine.world, [this.balls[i]]);
}
}
drawBalls() {
fill(this.color);
noStroke();
for(var i = 0; i<this.balls.length; i++){
drawVertices(this.balls[i].vertices);
}
}
}
在p5.js的‘Function Setup()’中调用‘setupBalls()’方法,在‘Function Draw()’中调用‘DrawBalls()’,如下所示:
function setup() {
createCanvas(1200, 600);
//create engine
engine = Engine.create();
//set world gravity to 0
engine.world.gravity.y = 0;
//balls
balls = new Balls(width / 2 + 100, 250, 8, color(200, 0, 0), 15);
balls.setupBalls();
}
function draw() {
background(125);
Engine.update(engine);
//balls
balls.drawBalls();
}
<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>
我试着使用嵌套的for循环来处理x和y位置,但我就是无法得到我想要的 pyramid 形状.
class Balls {
constructor(x, y, radius, color, ballCount) {
this.x = x;
this.y = y;
this.radius = radius;
this.color = color;
this.balls = [];
this.ballCount = ballCount;
this.option = {
restitution: 1,
friction: 0.01,
label: "ball"
};
}
setupBalls() {
for (var i = 0; i < this.ballCount; i++) {
var ball = Bodies.circle(this.x, this.y, this.radius, this.option);
this.balls.push(ball);
World.add(engine.world, [this.balls[i]]);
}
}
drawBalls() {
fill(this.color);
noStroke();
for (var i = 0; i < this.balls.length; i++) {
drawVertices(this.balls[i].vertices);
}
}
}
//module aliases
var Engine = Matter.Engine;
var World = Matter.World;
var Bodies = Matter.Bodies;
var Body = Matter.Body;
function setup() {
createCanvas(1200, 600);
//create engine
engine = Engine.create();
//set world gravity to 0
engine.world.gravity.y = 0;
//balls
balls = new Balls(width / 2 + 100, 250, 8, color(200, 0, 0), 15);
balls.setupBalls();
}
function draw() {
background(125);
Engine.update(engine);
//balls
balls.drawBalls();
}
<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>