I am using processing and I would like to create a game where the player is in a room and if they hit a wall they stop moving like a normal wall. However I don't really have any idea how to do this. With my current method once they hit the wall they can't move on the x axis anymore. Any help would be greatly appreciated.
PVector playerPosition;
PVector barrierPosition;
float velocity = 4;
boolean goLeft=false;
boolean goRight=false;
boolean goUp=false;
boolean goDown=false;
float playerWidth = 10;
float playerHeight = 10;
float barrierWidth = 10;
float barrierHeight = 600;
void setup() {
size(800,600);
rectMode(CORNER);
playerPosition = new PVector(200,200);
barrierPosition = new PVector(0,0);
}
void draw() {
background(255);
drawPlayer();
movePlayerPosition();
drawBarrier();
checkCollide();
}
//check for collision with barrier then stop player moving
void checkCollide() {
if (playerPosition.y <= barrierHeight + playerHeight && playerPosition.x <= barrierWidth + playerWidth)
{
println("COLLIDED");
playerPosition.x = barrierPosition.x + 10;
}
}
void drawPlayer() {
fill(255,0,0);
rect(playerPosition.x,playerPosition.y,playerWidth,playerHeight);
}
void drawBarrier() {
fill(0);
rect(barrierPosition.x,barrierPosition.y,barrierWidth,barrierHeight);
}
void movePlayerPosition() {
//moves up and down
if (goUp && playerPosition.y > 0)
{
playerPosition.y = playerPosition.y - velocity;
} else if (goDown && playerPosition.y < 598-playerHeight)
{
playerPosition.y = playerPosition.y + velocity;
}
//moves right and left
if (goLeft && playerPosition.x > 0)
{
playerPosition.x = playerPosition.x -velocity;
} else if (goRight && playerPosition.x <800-playerWidth)
{
playerPosition.x = playerPosition.x + velocity;
}
}
//if the keys are pressed move in that direction
void keyPressed() {
if (key == 'w') {
goUp=true;
} else if (key == 'a') {
goLeft=true;
} else if (key == 's') {
goDown=true;
} else if (key == 'd') {
goRight=true;
}
}
//if the keys are released stop moving
void keyReleased() {
if (key == 'w') {
goUp=false;
} else if (key == 'a') {
goLeft=false;
} else if (key == 's') {
goDown=false;
} else if (key == 'd') {
goRight=false;
}
}
Simple answer first; Your checkForCollide
method should return a boolean instead of been void, then you can use this method with your movePlayerPosition
one and only perform the X axis movement when there has been no collision.
Now, in a more complete answer; You should study a little more about the subject, there are a lot of patterns and libraries to better and easier handle this topic. I recommend you the Nature of code, you can get this pdf for free and you have a lot about the use of physic libraries from chapter 5 and on, also lots of samples about programming games.
Hope this helps and good luck. Regards Jose