Как кодировать (как показано ниже), чтобы красный шар не выходил за границы? - PullRequest
0 голосов
/ 03 июня 2019

При перетаскивании в верхний левый, правый угол и нижний левый красный шар будет выходить за границы.Как сделать так, чтобы он оставался в пределах?

Код ниже:

boolean goUp;
int y = height / 2;
int x = width / 2;
int xbound = 50;
int ybound = 50;
int shipSize = 40;
int myFrameRate = 30;
float easing = 0.05;


void setup() {
  frameRate(myFrameRate);
  fullScreen();
  background(0, 0, 0);
  textSize(20);
}

void draw() {
  clear();
  drawBoundary();
  getCommand();
  checkBoundary();
  drawShip();
  placeText();
  fill(255, 255, 255);
  textSize(50);
  text("mouseX:" + mouseX, width - 400, 50);
  text("mouseY:" + mouseY, width - 400, 100);

}

void placeText() {
  text("Time Elapsed: " + frameCount / myFrameRate, xbound, 40);
}

void checkBoundary() {
  if (y >= (height - ybound - shipSize)) y = height - ybound - shipSize;
  if (x >= (width - xbound - shipSize)) x = width - xbound - shipSize;
  if (x <= xbound + shipSize) x = 0 + xbound + shipSize;
  if (y <= ybound + shipSize) y = 0 + ybound + shipSize;
}

void getCommand() {
  if (keyPressed) {
    switch (keyCode) {
      case UP:
        y = y - 10;
        break;

      case DOWN:
        y = y + 10;
        break;

      case LEFT:
        x = x - 10;
        break;

      case RIGHT:
        x = x + 10;
        break;

      default:
        y = y;
        x = x;
        break;
    }
  }
}

void drawBoundary() {
  strokeWeight(5);
  stroke(50, 50, 50);
  line(xbound, ybound, width - xbound, ybound);
  line(xbound, height - ybound, width - xbound, height - ybound);
  line(xbound, ybound, xbound, height - ybound);
  line(width - xbound, ybound, width - xbound, height - ybound);
}

void drawShip() {
  strokeWeight(shipSize);
  stroke(255, 0, 0);

  if ((mouseX > width - 200) && (mouseY < height - 200)) {
    ellipse(width - 100, mouseY, shipSize, shipSize); // right side 
  } else if ((mouseX > width - 200) && (mouseY > height - 200)) {
    ellipse(width - 100, height - 100, shipSize, shipSize); // right bottom 
  } else if ((mouseX < width - 200) && (mouseY > height - 200)) {
    ellipse(mouseX, height - 100, shipSize, shipSize); // bottom
  } else if (mouseY < 100) {
    ellipse(mouseX, 100, shipSize, shipSize); // top
  } else if (mouseX < 100) {
    ellipse(100, mouseY, shipSize, shipSize); // left
  } else {
    ellipse(mouseX, mouseY, shipSize, shipSize);
  }

}

1 Ответ

0 голосов
/ 03 июня 2019

После switch in getCommand() вы вызываете существующую функцию checkBoundary()

...