For this assignment I was inspired by a video I took during the summer break of a group of ducks that left the lake in search for food. Every time people tossed seeds they ran as group towards them.
I attempted to mimic their movement in my code assigning each duck different acceleration while still having them all move in the same direction. I decided to attach to the mouse’s movement seeds to indicate what it is that the ducks are following.
The code was relatively simple however there was one section that was somewhat challenging for me to explore, that is, regarding the bounce back of the ducks. Initially before measuring the distance between the ducks and limiting their movement to avoid their overlap, the ducks lied on top of each other making their movement unrealistic.
Below is a snippet of the part of the code I found challenging:
for (let singleDuck of newDuck) { if (singleDuck !== this) { //measures distance between ducks let distance = p5.Vector.dist(singleDuck.position, this.position); if (distance < (this.radius *2)) { // Calculate the overlap amount let overlap = (this.radius *2) - distance; // Calculate the vector from this duck to the new duck let direction = p5.Vector.sub(this.position, singleDuck.position); direction.normalize(); // Calculate the bounce back force let collide = p5.Vector.mult(direction, overlap * 0.1); // Apply bounce back to the duck by adding value to acceleration this.acceleration.add(collide); } } }
First I made the move method of the Duck class specific to the argument newDuck, that is, it runs in relation to the newDuck variable. I did that because I need it to check for the collisions while handling the movement of the ducks.
Then in this method I created a for loop that runs through all the variables ‘singleDuck’ of the collection ‘newDuck’. In this for loop there is an if statement that runs as long as ‘newDuck’ is not being compared by itself ‘this’. This if statement checks for the distance between the ducks and ensures they do not overlap but rather collide and bounce. It does so by detecting their direction, and scaling the magnitude of it then adding to the value of acceleration. This leads to a more realistic and natural movement for the ducks.
Reflection and Ideas:
I am quite proud of how this code turned out. I think in the future I could elements that show more interactivity between the ducks and the seeds. This could be done through the seeds disappearing gradually as the ducks come across them. This at the moment is not something I know how to accomplish but I look forward to learning it.
Below is the code for reference:
https://editor.p5js.org/dhabialhosani/sketches/iLiewRjl7