Gravity

gravity-art

After exploring some the ways code can be used to generate really intriguing art the last few weeks, I knew I wanted to incorporate gravity into one of my projects and use the natural arcing that would result to create something visually striking. I figured I would incorporate if() statements by allowing the direction of gravity to change, and would incorporate a button to allow the user to change the gravity’s strength by clicking.

I don’t think I fully appreciated how challenging coding a physics concept like gravity would be. It took a long time to figure out that I required separate variables for the position and velocity of the ball in both directions, so that gravity could change velocity while velocity would change position. I understand the underlying derivatives/integrals that connect the three, so that made coding it much easier.

I initially ignored the x direction and attempted to get a ball to bounce as if under the influence of gravity in the y direction. Once I accomplished that, I added a variables for xVel and xPos and incorporated them into the ball’s position. Once I got the motion the way I wanted it, I used if() statements to cause the ball to “bounce” and change color when it hit an edge.

I made the button control the strength of gravity by multiplying the value by -1 and adding a random value to it each time the button is clicked. I also update the value that controls the direction of gravity each time it is pressed, causing it to potentially change which side of the canvas is the “anchor.” This can lead to some very interesting direction and speed changes when the button is pressed. It also solves the issue of the ball getting “stuck” when gravity forces it all the way to the edge of the canvas. Clicking should change the direction of gravity and start the ball on its merry way again.

I decided to include a box that constantly shows the values of gravity’s strength and both velocities. This gives the user a good visual of how different values affect the trajectory of the ball. I wouldn’t say there is sufficient information for someone to learn anything from it, but it’s interesting for those who like to see how different values affect things in the physical world.

See the sketch here

Leave a Reply

Your email address will not be published.