For week 2 of Nature of Code, I wanted to revisit my week 1 project and make some small adjustments. Previously, I mentioned that I wanted to have the user control the shark using the arrow keys. Since this week was all about vectors, I decided to create a simple physics engine for movement, rather than rely on pixel movement (ie, x = x - 1).

A 'predator' object with a position and velocity. The initial position of the object is randomized within the canvas, and the initial velocity of the object is zeroed out in the beginning.

The 'show' function displays the predator as a red ellipse with a weight of 10 pixels. The conditional statements at the bottom prevent the ellipse from leaving the canvas boundaries.

The 'update' function adds the object velocity to the initial position so that the object can move. The 'move' function detects which keys are pressed by the user, and adjusts the velocity accordingly to apply a force to the object.

A new 'predator' object is created within the variable 'sharkie', and all three methods are initiated in the draw loop.
Here is the sketch of the movement physics without the fishes:
Although the changes were quite simple, it was eye-opening to be able to utilize vectors to create more realistic, smooth object movement. The usage of vectors allowed for my shark object to move move dynamically through space, as opposed to simply crunching through individual pixels in the x and y axis. In the future, I hope to add in an acceleration component to this, and possibly create a racing simulator.