Week 10 assignment: Proton-Electron Sandbox

Overview

The Proton-Electron Sandbox is an interactive simulation built using P5.js and Matter.js. It allows users to explore the behavior of charged particles, represented as balls, in an enclosed space. Balls can be either electrons (negatively charged) or protons (positively charged) and they interact with each other based on electromagnetic forces – like charges repel and opposite charges attract.

Files

  • index.html: The HTML file that hosts the canvas for the simulation.
  • Ball.js: Defines the Ball class representing charged particles.
  • Sketch.js: Contains the main logic for the simulation, including setup, draw loop, and event handling.

Ball.js

Class: Ball

Represents a charged particle in the simulation.

Constructor

  • x, y: The initial position of the ball.
  • radius: The size of the ball.
  • charge: The electrical charge of the ball (+1 for proton, -1 for electron).
  • options: Matter.js body options.

Methods

  • show(): Renders the ball on the canvas.
  • calculateForce(other): Calculates the electromagnetic force exerted on another ball.
  • applyForce(force): Applies a force vector to the ball.

Sketch.js

Global Variables

  • engine, world: Matter.js engine and world instances.
  • balls: Array holding all ball objects.
  • boundaries: Array holding boundary objects.

Function: setup()

Initializes the canvas, Matter.js engine, and world. Also sets up the boundaries.

Function: draw()

The main draw loop. Updates the physics engine, calculates and applies forces, and renders balls and boundaries.

Function: mouseClicked()

Handles mouse click events to create new balls at the cursor position with random charges.

Class: Boundary

Represents static boundaries in the simulation.

Constructor

  • x, y: Position of the boundary.
  • w, h: Width and height of the boundary.

Method

  • show(): Renders the boundary on the canvas.

Usage

To use the simulation, open index.html in a web browser. Click anywhere on the canvas to create new charged balls. Observe the interactions between the balls based on their charges.

Demo

Customization

  • Ball Properties: Modify the Ball class to change the appearance or behavior of the balls.
  • Force Strength: Adjust the force calculation in Ball.js to simulate different interaction strengths.
  • Boundary Configuration: Change the dimensions or positions of the boundaries in sketch.js.

Leave a Reply

Your email address will not be published. Required fields are marked *