Stuck with replicating the mouseover function

hello, i’m having some trouble constricting the box space that triggers a change in visuals. i’ve drawn an outline of the area i want the visuals/mouse to change within. as the cursor moves out of this box, it should return to normal as the conditions become false. it does this correctly past the bottom and right sides of the box, but it changes too soon near the origin in the top left corner.
link to preview: https://editor.p5js.org/georg2a/present/kIcojHyUF
thanks to anybody who takes the time to read/respond to this!

let deer;
let love;

let dx;
let dy;

let dSize=180;

let overdBox=false;
let dlocked=false;

function preload(){
  deer = loadImage("love.gif");
  love = loadImage("deer.gif");
}

function setup() {
  imageMode(CENTER);
  //rectMode(CENTER);
  createCanvas(600, 600);
  
  dx = 200;
  dy = 100;
}

function draw() {
  background(0);
  image(deer, width/2,height/2,600,600);
  
  if (
   mouseX > dx - dSize &&
   mouseX < dx + dSize &&
   mouseY > dy - dSize &&
   mouseY < dy + dSize
  ) {
    overdBox=true;
    if (!dlocked) {
      //deer.reset();
   image(love,width/2,height/2,600,600);
    }
  }
    else {
      //love.reset();
    image(deer,width/2,height/2,600,600);
      overdBox=false;
    }
  //noStroke();
  noFill();
  square(dx,dy,dSize);
 // square(100,100,dSize);
;  
  if (overdBox == true){
      cursor(HAND);
      } else {
        cursor(ARROW);
  }
}

moving the boolean logic out of the main sketch and into a separate function can help readability/reusability.

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

function draw() {
  background(220);

  if (mouseIsIn(50,80,100,140)) {
    fill(255, 0, 0)
  } else {
    fill(255)
  }
  rect(50, 80, 100, 140)
  
}

function mouseIsIn(x, y, w, h) {
  if (mouseX > x && mouseX < x+w && mouseY > y && mouseY < y+h) {
    return true
  }
  return false
}
2 Likes

I made a processing program that does that:

Code
void setup() {
  size(600,600);
}
void draw() {
  background(0);
  fill( ((inBounds(200,200,200,200,mouseX,mouseY))? color(255,0,0) : color(0,0,255)));
  rect(200,200,200,200);
  println(inBounds(200,200,200,200,mouseX,mouseY));
}
boolean inBounds(float x, float y, float w, float h, float px, float py) {
  return(px > x && py > y && px < x + w && py < y + h);
}

enter (top left corner x, top left corner y, rect width, rect height, position x (mouseX), position y (mouseY) )

thank you so much, it’s working now!

2 Likes

OR with line breaks:

boolean inBounds(float x, float y,
     float w, float h,
     float px, float py) {
  return
          px > x &&
          py > y && 
          px < x + w && 
          py < y + h;
}
1 Like