(processing) How do I move item along the mouse?

I know how to move a specific shape along with the mouse, but what if I want to move a whole baseball bat which was being drawn by many shapes along with the mouse?

Does it mean that every shape must have the same centerX=mouseX and centerY=mouseY, but it doesn’t seem possible since different shapes start at different coordinates.

int centerX=mouseX, centerY=mouseY, bodyW=30;

int bodyH=bodyW*5;

int quadX1= centerX-bodyW/2, quadY=centerY+bodyH/2;
int quadX2= quadX1+bodyW;
int quadX3= quadX2-bodyW/4, quadY1=quadY+bodyW;
int quadX4= quadX1+bodyW/4;

int handleX= centerX, handleY= quadY1;
int handleW= quadX3-quadX4, handleH= bodyW*4;

int tailX=centerX, tailY= handleY+handleH/2;
int tailW=(bodyW*5)/6, tailH=bodyW/2;

int lineX1=quadX4, lineX2=quadX3;
int lineY1=quadY1+tailH,lineY2=lineY1+tailH, lineY3=lineY2+tailH;

void setup(){
  size(670,590);
}

void draw(){
  background(#F0E679);
  drawItem(mouseX,mouseY);
}

void drawItem(int centerX, int centerY){
  noStroke();
  rectMode(CENTER);
  fill(255);
  rect(centerX,handleY,handleW,handleH);
  fill(#070640);
  rect(centerX,centerY,bodyW,bodyH,25,25,0,0);
  quad(quadX1,quadY,quadX2,quadY,quadX3,quadY1,quadX4,quadY1);
  ellipse(centerX,tailY,tailW,tailH);
  
  stroke(#EDAA59);
  strokeWeight(2);
  line(lineX1,lineY1,lineX2,lineY1);
  line(lineX1,lineY2,lineX2,lineY2);
  line(lineX1,lineY3,lineX2,lineY3);
}
1 Like

You’ve got the right idea by putting your logic into the drawItem() function. Basically you want to create a function that takes a position as an argument, and then you want to draw all of your shapes relative to that.

I think one thing that might be confusing you is that you have a bunch of logic at the top of your sketch. Keep in mind that this code only gets executed once, so variables like quadX1 and quadX2 are never recalculated. I think what you want to do is move that logic inside your function, so it’s recalculated each frame.

What I recommend is starting smaller. Get a function working that just draws a single point or line. Then add the next point or line. Get that working perfectly before moving on. Good luck!

1 Like