Im working on creating movable players and wall collisions for my maze game, but whenever I run the code my player model instantly flies itself upwards. I know it’s something within my collision function, but I’ve looked through it meticulously and I can’t seem to understand why.
class Wall{
float x;
float y;
float w;
float h;
int c;
Wall(float sx, float sy, float sw, float sh){
x = sx;
y = sy;
w = sw;
h = sh;
c = color(#205415);
}
void display(){
fill(#205415);
rect(x,y,w,h);
}
}
Wall [] walls;
class Player{
float x;
float y;
float diameter;
float speed;
int c;
Player(float tempx,float tempy){//Constructor
c = color(#800080);
speed = 7;
diameter=70;
tempx = 120;
tempy = 10;
x=tempx;
y=tempy;
}
void display(){//Display
fill(c);
ellipse(x,y,diameter,diameter);
fill(#636363);
ellipse(x-15,y+15,diameter/4,diameter/4);
ellipse(x+15,y+15,diameter/4,diameter/4);
}
//Helpers
float left(){
return x-diameter/2;
}
float right(){
return x+diameter/2;
}
float top(){
return y-diameter/2;
}
float bottom(){
return y+diameter/2;
}
}
//Global Definition
Player player;
void setup(){
size(1024,812);
background(0);
player = new Player(width/2,height/2);
walls = new Wall[5];
walls[0] = new Wall(0,160,404,20);
walls[1] = new Wall(484,160,600,20);
walls[2] = new Wall(384,160,20,406);
walls[3] = new Wall(484,160,20,240);
walls[4] = new Wall(542,320,160,240);
}//end Setup
void draw(){
background(150);
player.display();
print(player.y);
for (int i=0;i < walls.length; i++) {
walls[i].display;
playerWallCollide(player, walls[i]);
}
}//End Draw
void playerWallCollide(Player r1, Wall r2) {
//What is the distance of the player to the wall on the X axis
float distX = ((r1.x+r1.diameter/2)-(r2.x+r2.h/2));
//What is the distance of the player to the wall on the Y axis
float distY = ((r1.y+r1.diameter/2)-(r2.y+r2.h/2));
//What are the combined half widths
float combinedHalfWidths = r1.diameter/2+r2.w/2;
//What are the combined half heights
float combinedHalfHeights = r1.diameter/2+r2.h/2;
if (abs(distX) < combinedHalfWidths||abs(distY) < combinedHalfHeights) {
float overlapX = combinedHalfWidths - abs(distX);
float overlapY = combinedHalfHeights - abs(distY);
if (overlapX >= overlapY){
//correct y overlaps
if (distY < 0){
print("Player top inside wall");
//player top is inside wall
r1.y += overlapY;
}else{
print("Player bottom inside wall");
//player bottom is inside wall
r1.y = r1.y - overlapY;
}
}else{
//correct x overlaps
if (distX < 0){
//player left side is inside wall
r1.x += overlapX;
}else{
//player right side is inside wall
r1.x -= overlapX;
}
}//End correct X overlaps
}//End Combined Half Widths/Heights
}//End player wall collide
void keyPressed(){
if (key == 'w' && player.top() > 0){
player.y = player.y-player.speed;
}
else if (key == 's' && player.bottom() < height){
player.y = player.y+player.speed;
}
else if (key == 'a' && player.left() > 0){
player.x = player.x-player.speed;
}
else if (key == 'd' && player.right() < width){
player.x = player.x+player.speed;
}
}