Moving a shape by mouseClicked function

I would like to move a shape to wherever I have clicked on the canvas. This is my program. Please tell me what changes i need to make in this

int xPos;
int yPos;

void setup()

void draw()



void drawSquare()
   final int RECT_WIDTH=300;
  final int RECT_HEIGHT=200;
  final int RECT_POS_X=(width-RECT_WIDTH)/2;
  final int RECT_POS_Y=(height-RECT_HEIGHT)/2;

void mouseClicked()


you should use the mouse position values for the rectangle position

int square=20;
void setup(){ size(500,500);  background(80); rectMode(CENTER); }
void draw(){ }
void mouseClicked(){  background(80); rect( mouseX,mouseY,square,square); }
void mouseWheel(MouseEvent event) { square += event.getCount()*3; }

Do you understand your own code?
You are drawing a rectangle.
You have variables to record where the last mouse click was.

All you need to do is use those variables for the rectangle’s position.

It doesnt work . It just draws the position of the rectangle on those coordinates without clicking it

It’s hard to understand what you even want to do. As best as I can tell, you want something like this:

float x=-20, y=-20;

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

void draw() {
  rect(x, y, 20, 20);

void mousePressed() {
  x = mouseX;
  y = mouseY;

If this isn’t exactly what you want, you need to do a better job explaining what you are trying to accomplish.

Same remark as in your other post: Simple Circle and rectangle code doubt [Solved]