Android Development: Simple collision detection

For my App I need to know when a user drags a specified element on top of another element. For instance when they drag one of their attack cards to the deck of the oponnent. On top of that I also need to know if the current location will result in an attack movement or just in a drag in open space. In both situations the game should do something else. So how can we detect if the current location is resulting in an attack? Simple by using the Rect.intersects method like so

package eu.jeroensomhorst.myfirst.util;

import android.graphics.Rect;
import eu.jeroensomhorst.myfirst.game.ui.UICard;

public final class CardUtil {

	public static boolean touchedCard(UICard c1, UICard c2){
		if(!(c1 == null || c2 == null)){
			Rect rect1 = new Rect((int)c1.x,(int)c1.y,(int)c1.x+c1.getWidth(),(int) (c1.getHeight()+c1.y));
			Rect rect2 = new Rect((int)c2.x,(int)c2.y,(int)c2.x+c2.getWidth(),(int) (c2.getHeight()+c2.y));
			return intersect(rect1, rect2);	
		}
		return false;
	}
	
	public static boolean touchedCard(UICard c, float x, float y) {
		
		Rect cardLocation = new Rect((int) c.x, (int) c.y, (int) c.x
				+ c.getWidth(), (int) c.y + c.getHeight());
		Rect location = new Rect((int)x,(int)y,(int)x+200,(int)y+200);
		
		return intersect(location,cardLocation);
	}
	
	private static boolean intersect(Rect r1,Rect r2){
		return r1.intersect(r2);
	}
}

this class implements a few utility methods. They bassicaly to the same thing. They convert the given parameters into two Rect instances and call the intersect method of the first Rect.  With this little tip you can easily integrate some basic collision detection. with this knowledge we can easily find out if the current user is attacking the enemy and which card is being attacked with the following code:

for(UICard c: this.enemyFrontLine){
					if(CardUtil.touchedCard(currentlyTouchedCard, c)){
						enemyFrontLineCard  = c;
						break;
					}
						
				}

In this example we loop over the enemyfrontline cards and for every card we check if it intersects. If that is the case we break out of the loop and use the found card to do the stuff we want to do with it ( in my case find out which card has ‘won’ and respond accordingly.

 

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.