I am working on a simple game with topdown movement, but I am unable to get the collisions to work properly. I know the collision detection itself works, but the constraining of the player is where I fail. It gets close to working, but on the corners it still clips into the squares. Also, if I add more squares for the player to collide with, it fails completely. I am programming this game in Processing, which uses Java. Here is my code:
void Collide(float WallX,float WallY,float WallWidth,float WallHeight) {
this.WallX = WallX;
this.WallY = WallY;
this.WallWidth = WallWidth;
this.WallHeight = WallHeight;
float TestX = PosX;
float TestY = PosY;
if(PosX <= WallX) {
TestX = WallX;
CollideLeft();
}
if(PosX >= WallX+WallWidth) {
TestX = WallX+WallWidth;
CollideRight();
}
if(PosY <= WallY) {
TestY = WallY;
CollideUp();
}
if(PosY >= WallY+WallHeight) {
TestY = WallY+WallHeight;
CollideDown();
}
fill(255,0,0,150);
ellipse(TestX,TestY,16,16);
Dis = sqrt(sq(TestX-PosX) + sq(TestY-PosY));
println("Dis= ",Dis,", TestX= ",TestX,", PosX= ",PosX,", TestY= ",TestY,", PosY= ",PosY);
}
boolean CollideLeft() {
if(Dis <= Radius+5) {
//PosX = WallX-Radius;
return CollideLeft = true;
}
else {
return CollideLeft = false;
}
}
boolean CollideRight() {
if(Dis <= Radius+5) {
//PosX = WallX+WallWidth+Radius;
return CollideRight = true;
}
else {
return CollideRight = false;
}
}
boolean CollideUp() {
if(Dis <= Radius+5) {
//PosY = WallY-Radius;
return CollideUp = true;
}
else {
return CollideUp = false;
}
}
boolean CollideDown() {
if(Dis <= Radius+5) {
//PosY = WallY+WallHeight+Radius;
return CollideDown = true;
}
else {
return CollideDown = false;
}
}
void Move() {
if(MoveRight && !CollideLeft) {
MoveX(1);
}
if(MoveLeft && !CollideRight) {
MoveX(-1);
}
if(MoveDown && !CollideUp) {
MoveY(1);
}
if(MoveUp && !CollideDown) {
MoveY(-1);
}
}