# How to collision detection?

Hello

I try to make a Mario Bros Game. I need some help with the collision. It already detects collision by checking if the tiles around him are an object tile (tile with other value than -1). The problem is that there is still a gap between the character and the wall. I know why but I can not think of a way of solving this.

``````import ptmx.*;

Ptmx map;
PImage image;
boolean left, right, jump, crouch;
PVector position, velocity, origin;

void setup(){
size(1200,480);
map = new Ptmx(this, "map.tmx");
position = new PVector(0,0);
velocity= new PVector(4,4);
}
void draw(){
if(jump == true && !collision_detected(position, "up")){
position.y-=velocity.y;
}
if(left == true && !collision_detected(position, "left")){
position.x-=velocity.x;
}
if(crouch == true && !collision_detected(position, "down")){
position.y+=velocity.y;
}
if(right == true && !collision_detected(position, "right")){
position.x+=velocity.x;
}

background(map.getBackgroundColor());
map.draw(0,0);
image(image,position.x,position.y);
}
boolean collision_detected(PVector pPosition, String pDirection){
int x = 0;
int y = 0;
/*
case for when character is at pixel 16 because pixel 16 should be still in tile 0 but is in tile x + 1 because 16 / tile_size (16) is 1 ( tile = 1 )
*/
if((pPosition.x + image.width) % 16 == 0){
x = 1;
}
if((pPosition.y + image.height) % 16 == 0){
y = 1;
}
int character_left = (int)(pPosition.x / 16);
int character_right = (int)((pPosition.x + image.width) / 16 - x);
int character_top = (int)(pPosition.y / 16);
int character_bottom = (int)((pPosition.y + image.height) / 16 - y);
boolean any_collision = false;

int a = 0, b = 0;
if(pDirection.equals("left") || pDirection.equals("right")){
a = 0;
b = 1;
} else if(pDirection.equals("up") || pDirection.equals("down")) {
a = 1;
b = 0;
}

int i = character_left - b;
int k = character_right + b;
if(pDirection.equals("right")){
i = character_right + b; // set i to character_right because only right columns need to be checked for collision
} else if(pDirection.equals("left")){
k = character_left - b;
}
for(; i <= k; i++){
int j = character_top - a;
int l = character_bottom + a;
if(pDirection.equals("down")){
j = character_bottom + a; // set j to character_bottom because only bottom rows need to be checked for collision
} else if(pDirection.equals("up")){
l = character_top - a;
}
for(; j <= l; j++){
int tile_id = map.getTileIndex(0, i, j);
switch(tile_id){
case 0: case 1: case 2: case 3: case 4: case 5: case 6:
any_collision = true;
break;
default:
break;
}
}
}

return any_collision;
}
void keyReleased(){
if(key == 'w'){
jump = false;
}
if(key == 'a'){
left = false;
}
if(key == 's'){
crouch = false;
}
if(key == 'd'){
right = false;
}
}
void keyPressed(){
if(key == 'w'){
jump = true;
}
if(key == 'a'){
left = true;
}
if(key == 's'){
crouch = true;
}
if(key == 'd'){
right = true;
}
}
``````