A tutorial on creating circular patterns within a pyramid structure using p5.js and matter.js

I've been attempting to create a pyramid shape using multiple circles, similar to this: balls in pyramid shape

To achieve this, I've developed a 'Balls' class:

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

The 'setupBalls()' method needs to be called within the 'function setup()', while 'drawBalls()' should be invoked inside 'function draw()' of p5.js as shown below:

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>

I experimented with adjusting the x and y positions using nested loops but couldn't achieve the desired pyramid shape.

Answer №1

I don't have much experience with matter.js, but here's a code snippet that uses nested for loops to create a triangle shape using circles in a pool ball rack arrangement:

let numBalls = [1, 2, 3, 4, 5]; // Balls per column
let ballsMax = 5;
let lenDisparity = 0;
let counter = 0;

// Building the grid by column
function circleGrid(l, t, diameter, hgap, vgap) {
  var x;
  var y; 
  for (let j = 0; j < numBalls.length; j++) {
    for (let k = 0; k < numBalls[counter]; k++) {   
      x = l + j*vgap;
      y = t + k*hgap;
      lenDisparity = ballsMax - numBalls[counter];
      if (lenDisparity > 0) {
        y += lenDisparity*hgap/2;
      }    
      fill(random(255),random(255),random(255));
      circle(x,y,diameter);
    }
    counter++;
  }
}

function setup() {
  createCanvas(400, 400);
  circleGrid(60,60,28,30,30);
}

function draw() {
}

CircleGridByColAndRow

This source code showcases the differences between building the grid by column and building it by row:

let numBalls = [1, 2, 3, 4, 5]; 
let ballsMax = 5;
let lenDisparity = 0;

function circleGridByCol(l, t, diameter, hgap, vgap) {
  var x;
  var y; 
  counter = 0;
  for (let j = 0; j < numBalls.length; j++) {
    for (let k = 0; k < numBalls[counter]; k++) {   
      x = l + j*vgap;
      y = t + k*hgap;
      lenDisparity = ballsMax - numBalls[counter];
      if (lenDisparity > 0) {
        y += lenDisparity*hgap/2;
      }    
      fill(random(255),random(255),random(255));
      circle(x,y,diameter);
    }
    counter++;
  }
}

function circleGridByRow(l, t, diameter, hgap, vgap) {
  var x;
  var y; 
  counter = 0;
  for (let k = 0; k < numBalls.length; k++) {
    for (let j = 0; j < numBalls[counter]; j++) {   
      x = l + j*vgap;
      y = t + k*hgap;
      lenDisparity = ballsMax - numBalls[counter];
      if (lenDisparity > 0) {
        x += lenDisparity*vgap/2;
      }    
      fill(random(255),random(255),random(255));
      circle(x,y,diameter);
    }
    counter++;
  }
}

function setup() {
  createCanvas(600, 250);
  circleGridByCol(60,60,28,30,30);
  circleGridByRow(250,60,28,30,30);
}

function draw() {
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Alter the language settings of the Datepicker feature in Material Angular 4

Need help changing the language of Datepicker in Material Angular. Struggling to locate this information in the Angular material 2 documentation. Check out this plunkr https://plnkr.co/edit/unzlijtsHf3CPW4oL7bl?p=preview <md-input-container> < ...

Having trouble importing Material UI and working with ClickAwayListener

For my current project, I am utilizing material-ui to implement the functionality for changing passwords. In this root file, I am importing several child components: Personalize.js import React, { useContext, useState } from 'react'; import Cook ...

How can we achieve the same functionality as React Native's { flex: 1 } in React JS?

I've been diving into React Native development, and now I'm exploring React.js for web applications. However, I'm facing a challenge in creating a simple View that takes up the entire screen to begin experimenting with different components. ...

Uncover hidden content by clicking a button with JavaScript

I need help with creating a function that hides additional content until a button is clicked. Currently, my script displays the content by default. How can I modify it to hide the content by default and only reveal it when the button is clicked? functi ...

Can the Angular.js scope be maintained while also making changes to the template?

I am currently facing a challenge with my directive. In the snippet below, I am attempting to extract content from a template, append it to the layout, and then compile it: var $template = angular.element("<div></div>"); $template.append($co ...

Execute a Node.JS query using an HTML select dropdown

My goal is to customize queries to a mySQL database based on the user's selection from select options on my website. Here is the HTML code: <select id = "year"> <option value = "yr" selected>Choose a Year</option> <option id = " ...

Ensuring Secure API Request Distribution

Currently, I am experimenting with distributed API requests. In PHP, I am developing a website that allows users to make requests on behalf of the server. The objective is to distribute these requests among users to maintain scalability even in high-traffi ...

Harnessing the power of the bluebird promise library

Within myPeople function, there is a promise function being called as shown below: var myPeople = function(){ var go; return new Promise (function(resolve){ User .getPeople() .then(function(allPeople){ ...

Adjust the background color of a specific list item when hovering over another list item

My dilemma lies in my inadequate knowledge to solve this issue: I have a dropdown menu embedded within a website. (View screenshot here: [SCREENSHOT]) The desired outcome is for the background color of an icon on the main list to change when I navigate to ...

Show pagination control only when there are multiple pages in AngularJS using ui-bootstrap

Currently, I am working with ui-bootstrap pagination and facing an issue where the pagination controls are still visible even when all the results are displayed on a single page. A quick glance at the image below confirms this problem. It seems like a basi ...

io.emit is unable to send messages to all connected clients

Struggling to implement a feature in a socket.io game where players can leave the game, I'm facing an issue with io.emit only notifying the departing player. Here's the snippet from my socket.js: io.on("connection", sock => { sock.on(&ap ...

A see-through object appears only properly when viewed from one specific angle

I am currently working with THREE.js and the WebGL renderer, facing an issue with a self-transparent object in my scene. This object is composed of a single geometry with a basic material that includes a texture and has the transparent: true property enabl ...

Encountering a loading error with r.js while attempting to optimize

In my main.js file, I have the following configuration for Require.js: /*--- Setting up Require.js as the main module loader ---*/ require.config({ baseUrl: '/javascripts/libs/home/', waitSeconds: 0, paths : { jquer ...

Error alert: Object expected on OnClientClick in Microsoft JScript runtime

I was in the middle of a quick test when I encountered an error. At this point, I haven't implemented any C# code yet and my aspx code looks like this: <script language=javascript type="text/javascript"> function myOnClick() { ...

sending a selection of JSON string values to a jQuery function

I have a JSON string that contains different items, but I am only interested in the 'locked' array and would like to pass it to a jQuery function. The JSON string was generated using json_encode from PHP. {"ignored":[],"status":{"message":"succe ...

Exploring the power of jQuery and Ajax together

Today seems to be one of those days where even the simplest tasks become a challenge. I'm sorry if this question has been asked before, but I'm struggling with a basic issue. I want to dynamically update text on a website using a text file, and w ...

Prevent the ability to add options dynamically to a drop-down select list

I have implemented a dynamic data retrieval feature from my database using jQuery's .getJSON function and appended the data to an HTML select drop-down list. The JavaScript code for this functionality is as follows: $.getJSON('url', f ...

I need help figuring out the right way to define the scope for ng-model within a directive

I found a straightforward directive to automate sliders: app.directive('slider', function() { return { restrict: 'AE', link: function(scope, element, attrs) { element.slider({ value: scop ...

Error with Google Maps Display

My goal is to achieve two things with the code snippet below: If the geocode process is unsuccessful, I want to prevent the map from being displayed (currently, I've only hidden the error message). If the geocode process is successful, I only want t ...

Bookshelf.js has implemented a new feature where it automatically encrypts passwords with bcrypt every time data is updated

My User Model is var Bookshelf = require('../../db').bookshelf; var bcrypt = require('bcrypt'); var Promise = require('bluebird'); var Base = require('./../helpers/base'); // Custom user model var Custom_User_Mod ...