# How do I detect if two sprites are being touched at the same time?

How do I detect if two sprites are being touched at the same time?

I was able to detect one sprite, but not if another sprite is being touched by the second pointer.

if(spr.getBoundingRectangles.contain(x,y))
{
//do this
}


Then, I created two Vector3 variables for the pointer coordinates, before iterating to each pointer.

for(int i = 0; i < Constants.MAX_POINTERS; i++)
{
if(Gdx.input.isTouched(i))
{
xy.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
xy1.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
WorldRenderer.camera.unproject(xy);
WorldRenderer.camera.unproject(xy1);

if(Spr.getBoundingRectangle().contains(xy.x, xy.y) &&
Spr1.getBoundingRectangle().contains(xy.x, xy.y))
{
score += 1;
}
}
}


What happens is that xy and xy1 are always the same, so when I touch the screen with the second pointer, they will just both switch to the new coordinates instead of xy and xy1 having different x and y values.

• Your calculations of xy and xy1 are identical; they happen at the same time with the same input parameters. One solution is to create an array of size MAX_POINTERS, then calculate xy[i].set( Gdx.input.getX(i), Gdx.input.getY(i), 0 ); WorldRenderer.camera.unproject( xy[i] ); – Paul Houx Oct 10 '15 at 16:01

Assuming the bounds of your sprites are rectangular:

• if your sprites don't rotate, you can detect if they overlap by direct comparison of their respective top, bottom, left and right bounding box coordinates. This assumes the bounding box is in world coordinates.
• if the bounding box is not in world coordinates, or your sprites will rotate and scale, you should transform the bounding box using the sprite's transform (model) matrix and do direct comparison again. If your game framework does not provide functions to transform the bounds, you can find sample code here.
• to figure out if the mouse pointer is inside the bounding box, especially when a sprite is rotated or scaled, the easiest way is to convert the pointer coordinate from window to world coordinates using the unproject function (once every time the mouse moves), then multiply the world coordinate by the inverse of the sprite's transform (model) matrix to find the local coordinate. You can then use the bounding box's "contain" function to test if it's inside.