Changing shapes for mouseX movement

Hello, I am new to P5.js and have made a simple sketch with an ellipse shape that follows the mouseX movement.

I would like to understand how to draw a different shape at mouseX based on three different mouseX movements on the canvas:

  • if mouseX is moving left from its previous mouseX coordinate then draw an ellipse at mouseX
  • if mouseX is moving right from its previous mouseX coordinate then draw a rect at mouseX
  • if mouseX is not moving at all from its previous mouseX coordinate then draw a triangle at mouseX

Thank you!

Hello, @afuria, and welcome to the Processing community!

Would you be able to post the code that you have thus far? This will help us help you. :smiley:

Is this homework?

Thanks for the welcome and your response @javagar! No, not homework, just a designer looking to have fun with code :slight_smile:

Here is where i’m at:

function setup() {
createCanvas(600, 400);
}

function draw() {
background(220);
fill(0);
noStroke();

var x = mouseX;
var size = 50;

ellipse(x, 300, size, size);
}

Would like to: draw the ellipse as mouse moves left, draw a rect as mouse moves right, and draw a triangle if there is no mouse movement.

many thanks!

1 Like

Hello @afuria

Sooo, this is not a solution, but it may be(?) a prompt in how to start to think about an approach to a solution…
Includes 2 states but not a third transitional triangle state, plus the tracking across the screen is not proper.

Code is in processing…

//////////////////////////////////////////

void setup() {
  size(600, 400);
}

void draw() {
  background(255);
  noFill();
  strokeWeight(3);
  rectMode(CENTER);

  float m = map(mouseX, 300, 600, 0, 600);
  float n = map(mouseX, 0, 300, 600, 0);
  int sz = 75;

  if (mouseX >= width/2) {
    ellipse(m, height/2, sz, sz);
  } else if (mouseX <= width/2) {
    rect(n, height/2, sz, sz);
  }
}

:nerd_face:

2 Likes

Hi @afuria,

Here’s some p5.js code that you can copy and modify. Try to add what is necessary to draw the triangle, and refine the rest to suit your needs and taste.

let curr_x, prev_x, size;
function setup() {
  createCanvas(600, 400);
  curr_x = width / 2;
  prev_x = curr_x;
  size = 50;
  rectMode(CENTER);
}

function draw() {
  /*
    - ellipse as mouse moves left
    - rect as mouse moves right
    - triangle if there is no mouse movement
  */
  background(220);
  fill(0);
  noStroke();
  prev_x = curr_x;
  curr_x = mouseX;
  if (curr_x < prev_x) {
    ellipse(curr_x, mouseY, size, size);
  } else if (curr_x > prev_x) {
    rect(curr_x, mouseY, size, size);
  } else {
    // draw triangle (for you to complete :) )
  }
}
2 Likes

Thanks @javagar, perfect!

1 Like