P5.js { gravity / velocity / acceleration / mass / applyForce() / mousePressed / mouseDragged / mouseReleased }
Click here to play the live project~!
Speaking of natural phenomena, the first thing that pops up in my mind is the Physics models I have learned in senior high school. And one that I would like to try this time is the spring with a bob.
First, to realize this model, I need to create two different objects, one is the spring, and the other is the bob. And I have to make the
Since I have to link the two objects together, I wrote a connect function to make the spring forces linked to the position of bob.
At the same time, I set the constraint of how long the spring can be to make it look closer to the reality world.
Minimum Length Constraint (minlen): If the distance between the bob and the anchor point of the spring is less than a specified minimum length (minlen), the method adjusts the bob’s position to ensure that the distance becomes exactly minlen. This prevents the bob from getting too close to the anchor point.
Maximum Length Constraint (maxlen): If the distance is greater than a specified maximum length (maxlen), the method adjusts the bob’s position to ensure that the distance becomes exactly maxlen. This prevents the bob from moving too far from the anchor point.
About the bob object, I practiced what we have learned in class about velocity, acceleration, and mass to apply a force.
Finally, to realise the effect of freely dragging the bob on canvas, I add 3 functions in the bob class:
handleClick(mx, my): to detect whether the user has clicked on the bob – let d = dist(mx, my, this.position.x, this.position.y) calculates the distance between the mouse click coordinates (mx, my) and the current position of the bob; and this.dragOffset.x = this.position.x – mx; and this.dragOffset.y = this.position.y – my records the offset between the position of the bob and the mouse click.
stopDragging(): to stop the dragging state of the bob;
handleDrag(mx, my): to update the position of the bob during dragging – if (this.dragging) { … } checks if the bob is currently being dragged; this.position.x = mx + this.dragOffset.x and this.position.y = my + this.dragOffset.y updates the position of the bob based on the mouse coordinates and the recorded offset.
Future Potentials: In the future, I would like to make the spring a soft line to create more elegant and changeable effects when dragging the bob.
Notes: I used an online emulator “Spring 2D” to test on different numbers of gravity, mass, damping, spring length to choose suitable ones to be applied in my project: https://www.myphysicslab.com/springs/2d-spring-en.html.