Hola EveryOne.

There are various methods/ways to detect a collision between two objects. Each having its own advantage and disadvantage and based on our requirement we implement one of the collsion detection algorithm.

Here i am not going to talk about collision algorithm. I am going to talk about determining the nearest object with which collision will take place. Suppose there are many objects across the screen and u have to detect the collision between your game character and those objects. And you run the algorithm to detect collision with each of every object in every frame. So it decreases the efficiency of your program. Its better to detremine the nearest object to your game character and detect collision with that determined nearest object.

Here i m using bounding rectangle concept for collision detection.

Code Example:

public static Sprite getNearestGroundSprite(ArrayList sprites,Sprite hero){
Sprite sprite=null;
float minDistance=9999;
if(hero!=null)
for(int i=0;iscreenWidth || (sprites.get(i).getSX()+sprites.get(i).getWidth()<0)){ continue; } else /* ignore all those objects which are located above the game character */ if(hero.getSY()>sprites.get(i).getSY()){
continue;
}
else
/* ignore all those objects that are located at the left side of game character */
if(hero.getSX()>(sprites.get(i).getSX()+sprites.get(i).getWidth())){
continue;
}
else
/* ignore all those objects that are located at right side of game character */
if((hero.getSX()+hero.getWidth())

Sprite is just a class representing characters of game. getSX() and getSY() returns the x and y coordinate location of that sprite. getWidth() simply returns the width of the sprite image.

In above code i am ignoring all those sprites that are located at left, right and top of my game character because i need bottom sprite to check collision with i.e when character falls down. This way the number of sprites decreases for checking collisions. You can write function for finding nearest left and right sprites also. You need to call this function at right place and when needed.

This is very simple and basic way i started and it gets the job done. You can write your own optimized code. This is how i started. I have written my optimized code for finding nearest sprite but right now i won't be posting it but i'l share it soon in near future.

Gracias.