I assume you are trying to prevent the cube from moving out of the window.
After you change the value of xPos and yPos, you can use an if statement to check whether they are still inside the window, and if not, force them to be equal to the last suitable value.
Here’s a modified version of your code that checks for one of the sides. You should be able to infer the other sides from there.
I made two other changes:
The size of the cube is a variable now, for reasons that should become clear once you try to implement the bottom and right walls
Redundant if statements in your keyPressed code have been removed or combined
int xPos = 25;
int yPos = 25;
int cubeSize = 15;
void setup() {
size(800,600,P2D);
//fullScreen();
}
void draw() {
//This is the background color.
background(75, 75, 75);
//This is the player’s controllable cube.
fill(250, 0, 0);
rect(xPos, yPos, cubeSize, cubeSize);
//These are the controls for the player’s cube.
if (keyPressed == true) {
if (keyCode == LEFT || key == 'a') {
xPos += -2;
}
else if (keyCode == RIGHT || key == 'd') {
xPos += 2;
}
else if (keyCode == UP || key == 'w') {
yPos += -2;
}
if (keyCode == DOWN || key == 's') {
yPos += 2;
}
// This checks for out of bounds position
if (xPos < 0) {
xPos = 0;
} // Put other boundary checks below...
}
}
It sounds like you’re looking for collision detection which allows you to detect when two shapes are overlapping. The idea is you’d check whether your player was overlapping with a wall, and not let them move in that direction.