如何使用p5js和matterjs绘制金字塔形状的圆

问题描述 投票:0回答:1

我正在尝试绘制多个金字塔形状的圆圈,如下所示:balls in pyramid shape

我做了这个“球”课:

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);
    }
  }
}

'setupBalls()' 方法在 p5.js 的 'function setup()' 中调用,'drawBalls()' 在 'function draw()' 中调用

我尝试使用嵌套 for 循环来调整 x 和 y 位置,但我只是无法获得我想要的金字塔形状。

javascript p5.js matter.js
1个回答
0
投票

尝试以下代码:

const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;

let engine;
let world;
let circles = [];

function setup() {
  createCanvas(800, 600);
  engine = Engine.create();
  world = engine.world;
  createPyramid(width / 2, height - 50, 10, 30, 30);
}

function draw() {
  Engine.update(engine);
  background(255);
  for (let circle of circles) {
    circle.show();
  }
}

function createPyramid(x, y, rows, radius, spacing) {
  for (let row = 0; row < rows; row++) {
    let cols = row + 1;
    let xOffset = -row * spacing / 2;

    for (let col = 0; col < cols; col++) {
      let xPos = x + col * spacing + xOffset;
      let yPos = y - row * spacing;
      let circle = new Circle(xPos, yPos, radius);
      circles.push(circle);
    }
  }
}

class Circle {
  constructor(x, y, radius) {
    this.body = Bodies.circle(x, y, radius);
    World.add(world, this.body);
    this.radius = radius;
  }

  show() {
    let pos = this.body.position;
    let angle = this.body.angle;
    push();
    translate(pos.x, pos.y);
    rotate(angle);
    fill(175, 200, 255);
    noStroke();
    ellipse(0, 0, this.radius * 2);
    pop();
  }
}

© www.soinside.com 2019 - 2024. All rights reserved.