1
votes

everyone. I'm a novice so excuse my ignorance. I basically want to stop registering mouseX depending on a condition. Let's say that I have a red area and inside that area a yellow circle. When the cursor is inside the red area I want the circle to track the moseX coordinates (while maintaining y-axis position) but I also want the circle to 'remember' the moseX coordinates as soon as the cursor leaves the area.

Here is the code I tried to do:

void setup ()
{
  size(500, 500);
}

void draw () 
{
  background(255);
  noStroke();
  fill(#F05757);
  quad(0, 0, 300, 0, 300, 200, 0, 200);
  fill(#EDF057);
  ellipse(motion(),100,40,40);
}

int motion ()
{
  int currentXValue = 0;
  int savedXValue = currentXValue;

  if (mouseX > 0 && mouseX < 300 && mouseY > 0 && mouseY < 200)
  {
    currentXValue = mouseX;
    savedXValue = currentXValue;
  } else {}

  return savedXValue;
}

When the cursor leaves the red area I don't want the circle to go back to X = 0, I want it to maintain the last stored x coordinates. I tried to make the variable currentXValue to track mouseX and saveXValue to remember the coordinates for when the cursor leaves the red area.

1

1 Answers

0
votes

You're creating the currentXValue variable inside the draw() loop and setting it equal to 0. Then you only change it if the mouse is inside the red area.

You need to keep track of the previous value of the currentXValue variable. In other words, you need to define the variable outside of the motion() function, at the sketch level:

int currentXValue = 0;

void setup ()
{
  size(500, 500);
}

void draw () 
{
  background(255);
  noStroke();
  fill(#F05757);
  quad(0, 0, 300, 0, 300, 200, 0, 200);
  fill(#EDF057);
  ellipse(motion(), 100, 40, 40);
}

int motion ()
{

  int savedXValue = currentXValue;

  if (mouseX > 0 && mouseX < 300 && mouseY > 0 && mouseY < 200)
  {
    currentXValue = mouseX;
    savedXValue = currentXValue;
  } else {
  }

  return savedXValue;
}

Now the currentXValue will persists between calls to the draw() function. Also note that your savedXValue is not needed.

Shameless self-promotion: I've written a tutorial on animation in Processing available here.