image description: A surreal pixel art scene of three goldfish floating around an underwater background. The background is light blue with a rocky terrain. Daisies are also drawn in the foreground.
I DID IT I DID IT!!!! Check out my sketch here! https://editor.p5js.org/mnk2970/sketches/7gZGHJRUY
I wanted to use this week's assignment to revisit last week's sketch, which I unfortunately did not end up finishing. My objective for last week was to have fish randomly swim around, and add more fish with each mouse press. This week, I decided to have the fish swim towards a spot determined by a mouse press. This would require me to use objects and arrays, which we learned about last week!
My objectives were to create an array for my fish images, an object to define what "fish" were, and to create several functions for my mouse press events.
I was reusing my assets from last week, so I didn't have to worry about rendering anything else. I started setting up my image files in a preload function, I established the background and one of the fish sprites that I intended to use (comments are in blue text).
//this is our image library
function preload() {
bg = loadImage('assets/bg.png');
fish1 = loadImage('assets/fish1.png');
Then, I created a fish function and an object to define my fishes movement. At the top, I declared
bubbles = new fish()
and created my fish function accordingly:
function fish() {
this.x = 0 //placeholder that can refer to bubbles, but doesnt limit it to the specific thigny, refers to x position of fish
this.y = 0
this.GoX = 0
this.GoY = 0
this.vx = 0
this.vy = 0
this.image = fish1;
this.moveFish = function() { // this defines a 'method' a function related to an object
this.x = this.x + this.vx; // moving fish in velocity, distance over time
this.vx = this.vx * random(0.8, 1) // this is our dampener, so the fish doesnt oscillate forever and ever and ever
this.vx = this.vx + (this.GoX - this.x) / 1500 // wave equation make fish go wheee
if (abs(this.GoX - this.x) > 10) // if it's to the left/right more than 10 pixels, wobble for swim effect
{
this.vx = this.vx + random(-1, 1)
}
this.y = this.y + this.vy;
this.vy = this.vy * random(0.8, 1) + (this.GoY - this.y) / 1500
if (abs(this.GoY - this.y) > 10) {
this.vy = this.vy + random(-1, 1)
}
}
this.drawFish = function() {
image(this.image, this.x, this.y)
}
this.mousePressed = function() {
// in this function, we'll establish a point for the fish to "swim" towards
this.GoX = mouseX
this.GoY = mouseY
}
}
At the top, I had to declare several values to orient the fish's location along the x/y coordinate (this.x/this.y), the mouse press's coordinate (GoX/GoY), and the fish's velocity (vx/vy).
At the bottom, in my draw function, I had the following code to render the fish and to call the object that I had made.
function draw() {
background(bg); // this is our background
for (f = 0; f < fishes.length; f++) {
fishes[f].moveFish() // instance.method
fishes[f].drawFish()
תגובות