September 29, 2016

example processing oop

This code uses instances of the PVector class (and the handy functions inside that class) to draw two eyes that follow the mouse. Creepy! :eyes: :ghost:

PVector leftEye;
PVector rightEye;

void setup(){
	size(200, 100);
	leftEye = new PVector(width*.25, height*.5);
	rightEye = new PVector(width*.75, height*.5);

void draw(){

	PVector mouseVector = new PVector(mouseX, mouseY);

	PVector leftPupil = leftEye.copy().add(mouseVector.copy().sub(leftEye).setMag(10));
	PVector rightPupil = rightEye.copy().add(mouseVector.copy().sub(rightEye).setMag(10));

	ellipse(leftEye.x, leftEye.y, 50, 50);
	ellipse(rightEye.x, rightEye.y, 50, 50);

	ellipse(leftPupil.x, leftPupil.y, 20, 20);
	ellipse(rightPupil.x, rightPupil.y, 20, 20);

eyes following mouse

We are doing a lot with just a couple lines of code, so let’s break that down into smaller steps. Take this line:

PVector leftPupil = leftEye.copy().add(mouseVector.copy().sub(leftEye).setMag(10));

This line can be broken up into its individual steps, that way we can better see what’s going on:

//copy the left eye so we don't change where we draw it when we call add()
PVector copyOfLeftEye = leftEye.copy();

//copy the mouseVector so we don't change it when we call sub()
PVector copyOfMouseVector = mouseVector.copy();

//subtract leftEye from copyOfMouseVector to get the direction to look
PVector difference = copyOfMouseVector.sub(leftEye);

//set the magnitude of the difference so the pupil doesn't go outside the eye
PVector scaledDifference = difference.setMag(10);

//add the scaledDifference to copyOfLeftEye so the pupil is centered around the eye
PVector leftPupil = copyOfLeftEye.add(scaledDifference);

eyes following mouse

eyes following mouse

eyes following mouse

Tweak Ideas

  • Try doing this without the PVector class. Hint: basic trig comes in handy!
  • Make the eyes look more realistic. Add iris colors, make them shaped like real eyes, add lashes, blinking, etc. Try to make it really pretty- or really creepy! :eyes: :ghost:
  • Make it so whenever the user clicks, a new eye is added.
  • Create faces that follow the mouse with their eyes, frown (or smile) when the mouse gets too close, look surprised when the user clicks, etc. Get creative!

Using Objects Examples


Happy Coding is a community of folks just like you learning about coding.
Do you have a comment or question? Post it here!

Comments are powered by the Happy Coding forum. This page has a corresponding forum post, and replies to that post show up as comments here. Click the button above to go to the forum to post a comment!