当您拖动到左上角,右上角和左下角时,红球将超出边界。如何使其停留在内部?
以下代码:
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);
}
}
答案 0 :(得分:-1)
在switch
中的getCommand()
之后,您调用了现有函数checkBoundary()